属性观察员
属性观察员回应房产价值的变化。
var myProperty = 5 {
willSet {
print("Will set to \(newValue). It was previously \(myProperty)")
}
didSet {
print("Did set to \(myProperty). It was previously \(oldValue)")
}
}
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5
- 在设置
myProperty之前调用willSet。新值以newValue的形式提供,旧值仍可作为myProperty使用。 - 设置
myProperty后调用didSet。旧值可用作oldValue,新值现在可用作myProperty。
注意: 在下列情况下不会调用
didSet和willSet:
- 分配初始值
- 在自己的
didSet或willSet中修改变量
didSet和willSet的oldValue和newValue的参数名称也可以声明为增加可读性:
var myFontSize = 10 {
willSet(newFontSize) {
print("Will set font to \(newFontSize), it was \(myFontSize)")
}
didSet(oldFontSize) {
print("Did set font to \(myFontSize), it was \(oldFontSize)")
}
}
警告: 虽然支持声明 setter 参数名称,但是应该小心不要混淆名称:
willSet(oldValue)和didSet(newValue)完全合法,但会使读者对你的代码感到非常困惑。