好吧,我正在阅读有关如何在 swift 中使用 willSet/didSet 的内容,我发现了一个关于 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 中父类(super class) 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 都无法访问该属性,所以无论如何谁会调用观察员?尝试读取/写入该属性甚至会导致编译器错误,因此在 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
虽然对您来说这似乎很自然,但文档必须明确记录此行为。
关于在调用 super.init 之前未调用 Swift 变量观察器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391886/