Swift 类的属性观察器 didSet willSet

本文通过示例代码详细介绍了Swift中类属性的观察器willSet和didSet的用法。在代码中,willSet用于在赋值前打印功率变化,didSet则在赋值后执行,当功率达到或超过最大值30时触发特定操作。然而,需要注意的是,willSet和didSet不会在构造函数中被触发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看下面代码

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){ // 将要赋值(括号里的是新值,也可以不填,直接用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)")
        }
        
    }
    
    init(currentPower: Int) {
        self.currentPower = currentPower
    }
}

var lightBulb2 = LightBulb(currentPower: 20)

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值