你能告诉我为什么要调用超类初始化器,因为我从不在子类中的初始化器中调用它吗?
关于初始化的两步过程,我认为编译器会抛出错误,因为我实际上没有调用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() ?
答案 0 :(得分:1)
如果您不自行拨打电话,指定初始值设定项中的编译器can synthesise a call至super.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)
}
}
请注意,此合成有一些限制,仅适用于:
init()
在所有其他情况下,您需要自己致电super.init
。