swift 属性观察器

概念

用来监视属性值变化,当属性值发生改变时能够对此做出响应。能够为除了延迟存储属性以外的其余存储属性添加属性观察器,也能够经过重载属性的方式为继承的属性(包括存储属性和计算属性)添加属性观察器。swift

  • willset 观察器会将新的属性值做为固定参数传入,在willSet的实现代码中能够为这个参数指定一个名称,若是不指定则参数仍然可用,这时使用默认名称 newValue 表示。
  • didSet 观察器会将旧的属性值做为参数传入,能够为该参数命名或者使用默认参数名 oldValue

使用

swift 属性拥有 set get 语法bash

var score : int {
    get { return getNum() }
    set { setBum(newValue) }
}
复制代码

willSetdidSet 分别在调用 set 方法以前和以后被调用,其意义在于有时候咱们须要在存储属性时作一些事情,例如通知某个对象,这个属性被改变了。若是只有 get set 方法,咱们就须要声明另一个字段来保存改动以前的值。借助 willSetdidSet 方法就不须要额外的字段了,直接使用 newValueoldValue 就能够了。markdown

class Student {
    var score: Int = 0 {
        willSet{
           print("will set score to \(newValue)")
        }
        didSet{
            print("did set score to \(oldValue)")
        }
    }
}
let student = Student()
student.score = 60
student.score = 99
复制代码

输出spa

will set score to 60
did set score to 0
will set score to 99
did set score to 60
复制代码

注意

  • willSetdidSet 观察器在属性初始化过程当中不会被调用,它们只会当属性的值在初始化以外的地方被设置时被调用。
  • 即便是设置的值和原来值相同,willSetdidSet 也会被调用。