Property Observer 正是您要找的:
属性观察者观察并响应属性的变化
价值。每次属性值被调用时,都会调用属性观察者
设置,即使新值与属性的当前值相同
价值。
假设你想观察a属性的变化,你可以实现为:
class Triangle {
var a: Int? {
willSet {
print("the new value is about to be: \(newValue)")
}
didSet {
print("the old value was: \(oldValue)")
}
}
var b: Int?
var c: Int?
// initialization stuff
// ...
}
调用(跟踪):
let myTriangle = Triangle()
myTriangle.a = 10
// this will print:
// the new value is about to be: Optional(10)
// the old value was: nil (nil because it's optional...)
// re-assign a new value:
myTriangle.a = 20
// this will print:
// the new value is about to be: Optional(20)
// the old value was: Optional(10)
如您所见,它会让您知道a 的值已更改,还告诉您旧值和新值是什么。
因此,通过实现 a 作为属性观察者,您可以在更改 a 属性的值时添加您的自定义行为;假设-例如-您想让c 等于a 的新值(如果它发生变化):
var a: Int? {
willSet {
print("the new value is about to be: \(newValue)")
b = newValue
}
didSet {
print("the old value was: \(oldValue)")
}
}
或者——另一个例子——你想在改变a的值时调用一个函数来做某事:
var a: Int? {
willSet {
print("the new value is about to be: \(newValue)")
doSomething()
}
didSet {
print("the old value was: \(oldValue)")
}
}
private func doSomething() {
print("doing something...")
}
有关更多信息,我建议查看Apple Documentation - “Property Observers”部分。
希望对您有所帮助。