日記
一瞬で4連休が終わってしまった.しかもこの週末は例のお気に入りの生主の放送がなかったのでこの先生きのこれる気がしない.週末じゃなくて終末だよ
今日書いたコード
class Sup { let str: String init() { print("Sup init") str = "str" } } class Sub: Sup { init(str: String) { print("Sub init", str) } convenience override init() { print("Sub convenience init") self.init(str: "some") } } Sub().str print("---") Sub(str: "some") // Sub convenience init // Sub init some // Sup init // --- // Sub init some // Sup init
初めて知ったこと
スーパークラスのイニシャライザが,引数を取らないDesignated Initializer1つだけのとき,サブクラスのイニシャライザの処理が終わったあとにそのイニシャライザが呼ばれる.
Chris_Lattner May '16
Two reasons:
1) No one wants to call super.init() when deriving from NSObject.
2) More generally, if there is exactly one DI in your superclass, and if it takes zero arguments, it is usually not interesting to have to call it, it is just boilerplate.
If you think that this is the wrong policy, please bring it up on swift-evolution. Note that this has been the behavior since Swift 1, and I haven’t heard any other serious complaints about it.
-Chris
https://forums.swift.org/t/super-init-called-automatically/2643/7