设置
get-and-set
如果要实现 gettable 和 settable 属性,可以使用常规语法。get
但是,如果您实现read-only
属性,您可以只使用语法。与setter
您一起获得newValue
财产。
class GetterSetter {
var theValue: Bool = false
var property: Bool {
get { return theValue }
set {
print("Value changed from \(theValue) to \(newValue)")
theValue = newValue
}
}
}
let getterSetter = GetterSetter()
getterSetter.property = true
getterSetter.property
// PRINTS:
// Value changed from 'false' to 'true'
设置
didSet
属性观察器用于在刚刚设置属性时需要执行代码的情况。实现didSet
你被赋予oldValue
代表以前的价值。
class DidSetter {
var property: Float16 = -1.0 {
didSet {
print("Value changed from \(oldValue) to \(property)")
}
}
}
let didSetter = DidSetter()
didSetter.property = 5.0
didSetter.property
// PRINTS:
// Value changed from -1.0 to 5.0
将设置
willSet
如果我们需要在设置属性之前执行代码,则使用属性观察器。实现willSet
您将被赋予newValue
代表它将成为的新属性值。
class WillSetter {
var property: String = "NO" {
willSet {
print("Value changed from \(property) to \(newValue)")
}
}
}
let willSetter = WillSetter()
willSetter.property = "YES"
willSetter.property
// PRINTS:
// Value changed from NO to YES