iOS程序猿阵线联盟-汇总各类技术干货iOS学习笔记

swift 属性观察器

2017-12-20  本文已影响166人  Inlight先森

概念

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

使用

swift 属性拥有 set get 语法

var score : int {
    get { return getNum() }
    set { setBum(newValue) }
}

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

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

输出

will set score to 60
did set score to 0
will set score to 99
did set score to 60

注意

上一篇 下一篇

猜你喜欢

热点阅读