gpt4 book ai didi

swift - 属性(property)观察员应该什么时候运行?有哪些异常(exception)情况?

转载 作者:搜寻专家 更新时间:2023-11-01 05:38:01 24 4
gpt4 key购买 nike

在以下情况下,属性观察者的行为让我感到惊讶。我知道观察者不会递归地调用自己,但这种行为似乎会转移到同一类的不同实例,甚至转移到不同子类的实例。

据我了解,属性观察器会在任何时候设置属性时运行,即使值没有改变,初始化时除外。该规则的异常(exception)情况到底是什么?如下所示,究竟什么时候会忽视属性(property)观察员?

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!?)

最佳答案

没有异常(exception)。我询问的行为是一个错误。我提交了a bug report对于那些跟踪其进展的人。

关于swift - 属性(property)观察员应该什么时候运行?有哪些异常(exception)情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com