加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 类的属性观察器 didSet willSet

发布时间:2020-12-14 06:26:40 所属栏目:百科 来源:网络整理
导读:先看下面代码 class LightBulb { static var maxPower:Int = 30 // 最大功率 var currentPower:Int = 0 { willSet(newCurrentPower){ // 将要赋值(括号里的是新值,也可以不填,直接用newValue) print("the power is change (abs(newCurrentPower - currentP

先看下面代码

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不会再构造函数中触发

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读