Swift 类的属性观察器 didSet willSet

前端之家收集整理的这篇文章主要介绍了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不会再构造函数中触发

原文链接:https://www.f2er.com/swift/322149.html

猜你在找的Swift相关文章