Chris
Chris

Reputation: 589

What is the following class function trying to achieve?

I am trying to convert the following piece of open source Objective C code to swift, but I am having a tough time wrapping my head around what this class function is trying to achieve. I know its a class method, I have added what I rewrote it at the bottom.

+ (instancetype)eventWithTitle:(NSString *)title day:(NSUInteger)day startHour:(NSUInteger)startHour durationInHours:(NSUInteger)durationInHours
{
    return [[self alloc] initWithTitle:title day:day startHour:startHour durationInHours:durationInHours];
}

Here is the method it is referencing if that helps.

- (instancetype)initWithTitle:(NSString *)title day:(NSUInteger)day startHour:(NSUInteger)startHour durationInHours:(NSUInteger)durationInHours
{
    self = [super init];
    if (self != nil) {
        _title = [title copy];
        _day = day;
        _startHour = startHour;
        _durationInHours = durationInHours;
    }
    return self;
}

Swift Version

    class func eventWithTitle(title: String, day: UInt32, startHour: UInt32, durationInHours: UInt32) {

        self.init(title: title, day: day, startHour: startHour, durationInHours: durationInHours)
    }

    init(title: String, day: UInt32, startHour: UInt32, durationInHours: UInt32) {

        self.title = title
        self.day = day
        self.startHour = startHour
        self.durationInHours = durationInHours

    }

The error I get when running this code is the following:

Result of initializer is unused.

Upvotes: 0

Views: 61

Answers (2)

dudeman
dudeman

Reputation: 1136

It's basically just a factory method. As you'll notice in the Objective-C version, the alloc'd/init'd instance is returned from that method. So you're going to want to change your Swift function to be more like:

class func eventWithTitle(title: String, day: UInt32, startHour: UInt32, durationInHours: UInt32) -> <className>{

    return <className>(title: title, day: day, startHour: startHour, durationInHours: durationInHours)
}

Upvotes: -1

vadian
vadian

Reputation: 285079

From the documentation:

Class Factory Methods and Convenience Initializers

For consistency and simplicity, Objective-C class factory methods are imported as convenience initializers in Swift. This allows them to be used with the same syntax as initializers.

That means, there is only the convenience initializer, the factory method is dropped.

init(title : String, day : Int, startHour : Int, durationInHours : Int)

Upvotes: 2

Related Questions