Swift 个变量观察者在 super.init 调用之前未被调用
Swift variable observers not called before super.init called
好吧,我正在阅读 willSet/didSet 是如何在 swift 中使用的,我发现了一个关于 apples swift 文档的注释,它对我来说没有任何意义我希望有人能解释一下。这是注释:
The willSet and didSet observers of superclass properties are called
when a property is set in a subclass initializer, after the superclass
initializer has been called. They are not called while a class is
setting its own properties, before the superclass initializer has been
called.
让我感到困惑的是,他们指出在 B 对 A 的 super.init 调用之前没有调用子类 B 中超类 A 属性的观察者。
class A {
var p: Bool
init() {
p = false
}
}
class B: A {
override var p: Bool {
didSet {
print("didSet p")
}
}
override init() {
p = true // Compiler error
super.init()
}
}
然而 属性 在那段时间甚至无法从 A 或 B 访问,所以谁会打电话给观察员呢?尝试 read/write 属性 甚至会导致编译器错误,因此在 Swift 中甚至不可能错误地做到这一点。我是不是遗漏了什么,或者这只是指出错误内容的误导性说明?
他们正在谈论以下场景:
class A {
var p: Bool {
didSet {
print(">>> didSet p to \(p)")
}
}
init() {
p = false // here didSet won't be called
}
}
class B: A {
override init() {
// here you could set B's properties, but not those inherited, only after super.init()
super.init()
p = true // here didSet will be called
}
}
B()
它将打印以下内容:
>>> didSet p to true
虽然对您来说这似乎很自然,但文档必须明确记录此行为。
好吧,我正在阅读 willSet/didSet 是如何在 swift 中使用的,我发现了一个关于 apples swift 文档的注释,它对我来说没有任何意义我希望有人能解释一下。这是注释:
The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.
让我感到困惑的是,他们指出在 B 对 A 的 super.init 调用之前没有调用子类 B 中超类 A 属性的观察者。
class A {
var p: Bool
init() {
p = false
}
}
class B: A {
override var p: Bool {
didSet {
print("didSet p")
}
}
override init() {
p = true // Compiler error
super.init()
}
}
然而 属性 在那段时间甚至无法从 A 或 B 访问,所以谁会打电话给观察员呢?尝试 read/write 属性 甚至会导致编译器错误,因此在 Swift 中甚至不可能错误地做到这一点。我是不是遗漏了什么,或者这只是指出错误内容的误导性说明?
他们正在谈论以下场景:
class A {
var p: Bool {
didSet {
print(">>> didSet p to \(p)")
}
}
init() {
p = false // here didSet won't be called
}
}
class B: A {
override init() {
// here you could set B's properties, but not those inherited, only after super.init()
super.init()
p = true // here didSet will be called
}
}
B()
它将打印以下内容:
>>> didSet p to true
虽然对您来说这似乎很自然,但文档必须明确记录此行为。