Calling super.init() in initializer of NSObject subclass in Swift

后端 未结 1 2051
渐次进展
渐次进展 2021-02-19 04:27

I\'m building an iOS app in Swift and drawing on the Lister sample project Apple provides.

Lister uses two model objects: List and ListItem. I found that both of them do

相关标签:
1条回答
  • 2021-02-19 04:50

    Even though I can't find a place in the documentation where this is described, what happens is that the default superclass initialiser is called at the end of the subclass initialiser if that is the only initialiser of the superclass, and it wasn't called explicitly.

    NSObject only has the default initialiser (init()); you can see that the superclass initialiser is called at the end of the subclass initialiser by attempting to reference self (eg. println(self)) in a constructor that does not call super.init(): You are not allowed to do it because the class is not fully initialised at that point.

    If you want to use self somewhere in the constructor, the object needs to be fully constructed at that point, so you need to call super.init() manually before then.

    0 讨论(0)
提交回复
热议问题