先看下面代码
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不会再构造函数中触发
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。