天天看點

[swift]初始化方法自己主動繼承

    子類預設不會繼承父類的初始化方法,然而,假設某種條件滿足的話。父類的初始化方法還是能夠繼承給子類。在通常情況下,這意味着你不必複寫父類的初始化方法。在安全的前提下能夠以最低的代價繼承父類的初始化方法。

    如果子類新增的stored properties 都提供了預設值。那麼提供了下面兩條規則:

規則1:

假設你的子類未定義不論什麼的指定初始化方法(新增便利初始化方法可有可無)。那麼子類會自己主動繼承父類的全部指定初始化方法。

規則2:

假設子類通過規則1。或者通過自己定義實作父類的全部指定初始化方法,那麼子類自己主動繼承父類的全部便利初始化方法。(子類以便利初始化方法覆寫父類的指定初始化方法也視為對父類的指定初始化方法的實作。

【注:Swift 的class 類型的初始化方法包含兩種類型。指定初始化方法(Designated Initializer)和便利初始化方法(Convenience Initializer)。預設是指定初始化方法。一個class類型至少提供一個指定初始化方法。)

原文:

As mentioned above, subclasses do not inherit their superclass initializers by default. However, superclass initializers are automatically

inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.

Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:

<dl></dl>

<dt></dt>

Rule 1

<dd></dd>

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.

These rules apply even if your subclass adds further convenience initializers.

NOTE

A subclass can implement a superclass designated initializer as a subclass convenience initializer as part of satisfying rule 2.

下一篇: 網絡層