2

Here's my code:

import Foundation


class Person: NSObject, NSCoding {

var name: String



init(name: String) {
    self.name = name
}

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

required convenience init?(coder aDecoder: NSCoder) {

    let name = aDecoder.decodeObjectForKey("name") as! String

    self.init(name: name)

}  
}


class Martin: Person {

 init() {
    self.init(name: "Martin")
}

required convenience init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

}

let p = Martin()

print(p.name)

For some reason I always end-up in a catch-22 situation, the only way i see making this work is to explicitly initialize all properties in required convenience init?(coder aDecoder: NSCoder) to able to remove the convenience and do super.init(coder: aDecoder) in Martin

I read about the init rules in Swift, still don't understand why Martin can't inherit the convenience init from Person in this case.

Tobi Nary
  • 4,566
  • 4
  • 30
  • 50
petard
  • 333
  • 1
  • 11

1 Answers1

0

Because the rules state that

  1. A designated initializer must call a designated initializer from its immediate superclass.
  2. A convenience initializer must call another initializer from the same class.
  3. A convenience initializer must ultimately call a designated initializer.
Tobi Nary
  • 4,566
  • 4
  • 30
  • 50
  • So there is no way of making it work without making `init?(coder aDecoder: NSCoder)` a non-convenience method? I thought using Rule 2 i could make it work somehow. Rule 2 `If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.` – petard Feb 19 '16 at 10:37
  • as always the solution is quite simple: `class Martin: Person { convenience init() { self.init(name: "Martin") } }` this way Martin is inheriting all the parent's initalizers – petard Feb 19 '16 at 10:53