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

前端 未结 4 964
暖寄归人
暖寄归人 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:25

    Yes the designated initializer need to delegate up, so it must call the super.init(). If you don't write the line, the compiler will do it for you.

    So you do not have to explicitly write super.init(...), but the subclass has to, even if only behind the curtain.

    But remember, in the first phase you need to set the properties in the subclass, then the super.init() must be called. In the second phase you may change all the inherited properties. I think super.init() is a perfect separator between phase 1 and phase 2.

    From the docs:

    Safety check 2

    A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.

提交回复
热议问题