LoginSignup
0
1

More than 1 year has passed since last update.

2段階初期化

Posted at

クラスのイニシャライザには、型の整合性を保った初期化を実現するために、3つのルールがあります。

・指定イニシャライザはスーパークラスの指定イニシャライザを呼ぶ
・コンビニエンスイニシャライザは同一クラスのイニシャライザを呼ぶ
・コンビニエンスイニシャライザは最終的に指定イニシャライザを呼ぶ

スーパークラスとサブクラスのプロパティの初期化順序を守るため、指定イニシャライザによるクラスの初期化は次の2段階に分けて行われます。
1、クラス内で新たに定義されたすべてのストアドプロパティを初期化し、スーパークラスの指定イニシャライザを実行する。スーパークラスでも同様の初期化を行い、大元のクラスまで遡る。
2、ストアドプロパティ以外の初期化を行う

class User {
    let id: Int

    init(id: Int) {
        self.id = id
    }

    func printProfile() {
        print("id: \(id)")
    }
}

class RegisteredUser: User {
    let name: String

    init(id: Int, name: String) {
        // 第一段階
        self.name = name
        super.init(id: id)

        // 第二段階
        self.printProfile()
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1