UIViewController
class defines a single designated initializer, init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
and no convenience initializers, however, it is possible to write the following line of code and have it compile (Xcode 6.1.1)
let vc = UIViewController()
How is this possible?
According to the Swift book, here are the rules of initializer inheritance
Rule 1 If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
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.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
Therefore UIViewController
couldn't have inherited the init()
method from its ancestor superclass NSObject
, then where does the initializer come from?
On a different note, because every swift class must ultimately call its designated initializer, doesn't that mean initWithCoder:
will also end up calling init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
? However that doesn't seem to be the case in practice.
initWithCoder:
method because it conforms toNSCoding
which requires it. Not sure why it has a default initializer... Since it's an Objective-C class and not a Swift class, it's not required to follow the rules of Swift inheritance, so it doesn't have to call the designated initializer. Were you to rewrite it in Swift you'd probably have to. A large part of what swift is trying to do is clarify many of these arcane rules exceptions. - David Berry