在OC中我们可以重写Set方法来监听属性的改变,Swift中可以通过属性观察者来监听和响应属性值的变化,我们通过设置属性观察器(Property Observer)
1、willSet: 会传递新值,默认叫 newValue
2、didSet:会传递旧值, 默认叫 oldValue
3、在初始化器中设置属性值不会触发willSet和didSet
4、在属性定义时设置初始值也不会触发willSet和didSet
class Persion
{
var name:String = ""
var age:Int = 5{
willSet{
print("newValue=\(newValue) age=\(age)")//newValue=10 age=5
}
didSet{
print("oldValue =\(oldValue) age =\(age)") //oldValue =5 age =10
}
}
}
let pe = Persion()
pe.age = 10