繼承 – 一個快速的子類*總是*必須呼叫super.init()
如果我有一個迅捷的子類:
>不需要訪問自己
>不需要自己訪問任何屬性
我還需要在子類的init()方法中呼叫super.init()?
*注意:由於上述1和2中列出的細節,這是一個不同於問題和回答ofollow,noindex" target="_blank">here on SO 的問題.
從文件:
Designated initializers must call a designated initializer from their immediate superclass.
另外,關於自動初始化器繼承:
Assuming that you provide default values for any new properties you
introduce in a subclass, the following two rules apply:
Rule 1If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initializers.
Rule 2If 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.
所以你的問題的答案如下:
您的子類將始終呼叫您的超類的指定的初始化程式.如果不編寫初始化程式並且編譯器不會抱怨,那麼它使用了自動初始化程式繼承.如果你寫一個初始化器,但是沒有明確地呼叫一個相關的上游(或sidestream)初始化器,那麼這將在你的初始化器結束時自動完成.
此外,連結初始化程式的工作方式是在兩階段過程中.在第一階段,它從子類開始到超類,將預設值分配給任何引數.在第二階段,該過程是向後執行的,從超類開始,以您的子類結束,引數的自定義完成和覆蓋.
這意味著您必須絕對首先在每個init()中設定變數,然後可以呼叫(或不呼叫)super.init()並執行自定義程式碼.所以就像上面提到的那樣,如果你想讓super的init在開始執行,可以考慮在開始建立你的變數之後的’開始’:
class a { var name: String init() { name = "james" println("a") } } class b: a { let title: String override init() { title = "supervisor" super.init() self.name = "john" println("b") } } let x = b()
這將列印a,然後b.
http://stackoverflow.com/questions/25257224/does-a-swift-subclass-always-have-to-call-super-init