在下列情况下,财产观察员的行为让我感到惊讶。我理解观察者不会递归地调用自己,但是这种行为似乎会延续到同一个类的不同实例,甚至延伸到不同子类的实例。
据我了解,属性观察者在设置属性时运行,即使值没有改变,初始化除外。这条规则的例外究竟是什么?财产观察员究竟会被忽视,如下所示?
var observersCalled = 0
class ClassOne {
var relatedOne: ClassOne?
var relatedTwo: ClassTwo?
var property: String = "Initial" {
didSet {
observersCalled += 1
relatedOne?.property = property
relatedTwo?.property = property
}
}
}
class ClassTwo {
var property: String = "Initial" {
didSet {
observersCalled += 1
}
}
}
class Subclass: ClassOne {
override var property: String {
didSet {
observersCalled += 1
}
}
}
let thing = ClassOne()
thing.relatedOne = ClassOne()
thing.property = "New Value"
print(observersCalled) //1 (really?)
observersCalled = 0
thing.relatedOne = nil
thing.relatedTwo = ClassTwo()
thing.property = "Another Value"
print(observersCalled) //2 (makes sense)
observersCalled = 0
thing.relatedOne = Subclass()
thing.relatedTwo = nil
thing.property = "Yet Another Value"
print(observersCalled) //1 (really!?)