willSet 会在该值被存储之前被调用
didSet 会在一个新值被存储后调用
如果你实现了一个willSet观察者,新的属性值会以常量形式参数传递。你可以在你的willSet实现中为这个参数定义名字,如果你没有为他命名,那么他会使用默认的名字newValue
如果你实现了一个didSet观察者,一个包含旧属性的常量形式参数将会被传递。你可以为他命名,也可以使用默认的形式参数名 oldValue 如果你在属性自己的didSet观察者里给自己赋值,你赋值的新值就会取代刚刚设置的值
//: A UIKit based Playground for presenting user interface
import UIKit
class StepCounter{
var totlaSteps:Int = 0 {
willSet(newTotalSteps){
print("About to set totalSteps to \(newTotalSteps)")
}
didSet{
if totlaSteps > oldValue {
print("Added \(totlaSteps-oldValue)")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totlaSteps=200
stepCounter.totlaSteps=220
stepCounter.totlaSteps=241
About to set totalSteps to 200
Added 200
About to set totalSteps to 220
Added 20
About to set totalSteps to 241
Added 21
观察者属性能力同样对全局变量和局部变量有效。全局变量是定义在任何函数、方法、闭包、或者类环境之外的变量。局部变量是定义在函数、方法、或者闭包环境之中的变量。
//: A UIKit based Playground for presenting user interface
import UIKit
var totlaSteps:Int = 0 {
willSet(newTotalSteps){
print("About to set totalSteps to \(newTotalSteps)")
}
didSet{
if totlaSteps > oldValue {
print("Added \(totlaSteps-oldValue)")
}
}
}
totlaSteps = 10
if totlaSteps == 10 {
print("ten")
}
About to set totalSteps to 10
Added 10
ten
类型属性
使用static 关键字来定义属性类型,对于类类型的计算类型属性,你可以使用class关键字来允许子类重写父类的实现
//: A UIKit based Playground for presenting user interface
import UIKit
class SomeClass{
static var storedTypeProperty = "Some value."
static var computedTypeProperty:Int{
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
class SomeClass2:SomeClass{
override class var overrideableComputedTypeProperty: Int {
return 106
}
}
let classSome=SomeClass()
标签:totalSteps,didset,willset,print,set,var,totlaSteps,属性 From: https://blog.51cto.com/u_14523369/6113218