Swift 类的属性观察器 didSet willSet

先看下面代码

class LightBulb {
    static var maxPower:Int = 30 // 最大功率
    var currentPower:Int = 0 {
        
        willSet(newCurrentPower){ // 将要赋值(括号里的是新值,也可以不填,直接用newValue)
            print("the power is change \(abs(newCurrentPower - currentPower))")
        }
        
        
        didSet(oldCurrentPower) { // 已经赋值(括号里的是旧值,也可以不填,直接用oldValue)
            if currentPower == LightBulb.maxPower {
                print("Pay attention,the current power go to The highest power")
            }
            
            else if currentPower > LightBulb.maxPower {
                print("Pay attention,the current power More than the highest power")
                currentPower = oldCurrentPower // 附上旧值
            }
            
            print("the current power is \(currentPower)")
        }
    }
}

var lightBulb = LightBulb()
lightBulb.currentPower = 20
lightBulb.currentPower = 30
lightBulb.currentPower = 40

打印结果

the power is change 20

the current power is 20

the power is change 10

Pay attention,the current power go to The highest power

the current power is 30

the power is change 10

Pay attention,the current power More than the highest power

the current power is 30


代码中willSet意思是即将赋值,在后面的括号里写即将赋值的代码,didSet的意思是赋值完毕,(在后面的括号里写赋值完毕的代码)

代码中定义了一个功率最大为30的灯泡,在willSet中,打印上次灯泡功率和当前功率差的绝对值,在didSet中,当灯泡的当前功率等于30的时候打印一段提示,当功率大于30的时候,把灯泡的当前功率设置成最大功率并打印一段提示


下面我更改了上面的代码

class LightBulb {
    static var maxPower:Int = 30 // 最大功率
    var currentPower:Int = 0 {
        
        willSet(newCurrentPower){ // 将要赋值(括号里的是新值,the current power More than the highest power")
                currentPower = oldCurrentPower // 附上旧值
            }
            
            print("the current power is \(currentPower)")
        }
        
    }
    
    init(currentPower: Int) {
        self.currentPower = currentPower
    }
}

var lightBulb2 = LightBulb(currentPower: 20)

但是下面并没有打印任何内容,说明didSet,willSet不会再构造函数中触发

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...