类属性的监听

class Person {
    var name : String = "" {
        // 属性监听器: 选中其中之一即可
        // 监听属性即将发生改变: 还没有改变
        willSet {
            print(newValue)
            print(name)
        }

        // 监听属性已经发生改变: 已经改变
        didSet {
            print(oldValue)
            print(name)
        }
    }
}

当执行代码:

name = "123"
print("------------")
name = "456"

结果为:

newValue 123
name 
oldValue 
name 123
------------
newValue 456
name 123
oldValue 123
name 456

也就是说: 在didSet和willSet里面, 默认有newValue和oldValue两个属性, 来保存name属性的改变前以及改变后的值

继承时, 方法的调用顺序

子类的 willSet
父类的 willSet
父类的 didSet
子类的 didSet

猜你喜欢

转载自blog.csdn.net/u012678352/article/details/54612488
今日推荐