Does a swift subclass *always* have to call super.init()

前端 未结 4 963
暖寄归人
暖寄归人 2021-01-30 21:46

If I have a swift subclass that:

  1. doesn\'t need to access self
  2. doesn\'t need to access any properties on self

Do

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 22:30

    No, you don't have to.

    Assume you have the following classes.

    class a {
        let name: String
    
        init() {
            name = "james"
        }
    }
    
    class b: a {
        let title: String
    
        override init() {
            title = "supervisor"
        }
    }
    

    If you instantiate a variable with

    let myVar = b()

    Then,

    • override init() in b will be called
    • then the init() in a will be called

    Even though you didn't explicitly call super.init().


    This has been confirmed by Chris Laettner on the swift-user's email list. It kicks in when your super class has a single designated initializer with a zero-argument init. This is why you don’t have to call super.init() when deriving from NSObject.

    *Thanks to Wingzero's comment below

提交回复
热议问题