bearMountain bearMountain - 2 months ago 16
Swift Question

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

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 I still have to call
super.init()
in the subclass's
init()
method?

*Note: This is a different question than the one asked and answered here on SO because of the specifics listed in 1 and 2 above.

Answer

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