Swift初始化器继承

时间:2018-01-15 08:13:25

标签: swift initialization

你能告诉我为什么要调用超类初始化器,因为我从不在子类中的初始化器中调用它吗?

关于初始化的两步过程,我认为编译器会抛出错误,因为我实际上没有调用super.init()

class Superclass {
    var a: Int

    init() {
        self.a = 1
    }
}

class Subclass: Superclass {
    var b: Int

    override init() {
        self.b = 2
    }
}

var subclass = Subclass()
print(subclass.b)
// Print 2
print(subclass.a)
// Print 1 => How is it possible as I never call super.init() ?

1 个答案:

答案 0 :(得分:1)

如果您不自行拨打电话,指定初始值设定项中的编译器can synthesise a callsuper.init()。因此,在您的情况下,编译器会有效地将您的代码转换为:

class Superclass {
  var a: Int

  init() {
    self.a = 1
  }
}

class Subclass : Superclass {
  var b: Int

  override init() {
    self.b = 2
    super.init() // synthesised by the compiler
  }
}

这也适用于你没有覆盖超类的情况。 init()

class Subclass : Superclass {
  var b: Int

  init(b: Int) {
    self.b = b
    super.init() // also synthesised by the compiler (try removing)
  }
}

请注意,此合成有一些限制,仅适用于:

  1. 超类只有一个指定的初始化
  2. 此指定的初始化程序没有任何参数,即init()
  3. 在所有其他情况下,您需要自己致电super.init

相关问题