Pavel
Pavel

Reputation: 766

Swift: Required initializer giving me an error message

I have a class named Alarm inheriting from NSObject, and in it, I have a property I'm having an issue with, alarmLastTriggeredDate:

class Alarm: NSObject {
    var alarmLastTriggeredDate: NSDate

    override init() {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(alarmLastTriggeredDate, forKey: "alarmLastTriggeredDate")
    }

    required init(coder aDecoder: NSCoder) {
        if let alarmLastTriggeredDateDecoded = aDecoder.decodeObjectForKey("alarmLastTriggeredDate") as? NSDate
        {
            alarmLastTriggeredDate = alarmLastTriggeredDateDecoded
        }
    }
}

I'm new to Swift, and not sure why I'm getting the following errors:

@override init: Property 'self.alarmLastTriggeredDate' not initialized at super.init call
@required init: Property 'self.alarmLastTriggeredDate' not initialized at implicitly generated super.init call

It seems the only way to fix this problem is to initialized it in both places, but that's redundant code, and seems wrong. Am I missing something?

Upvotes: 1

Views: 119

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

The compiler must be sure that every non optional property is successfully initialized:

  • before a call to a super init is performed
  • AND before the object initialisation has been completed

That's why you need to populate alarmLastTriggeredDate inside bot initializers.

And no, it's not redundant code since someone could use one of the 2 initializers to create your Alarm object.

Upvotes: 1

Related Questions