willSet和didSet这两个特性来监视属性的除初始化之外的属性值变化,一个监听改变之前 一个监听改变之后的属性
简单举例
class Person : NSObject{
var variable1 : Int = 0 {
willSet {
print("before change variable2: \(variable2)")
}
didSet {
if variable1 > 10 {
variable2 = 30;
}
print("after change variable2: \(variable2)")
}
}
var variable2: Int? = 10
var variable3: Int {
get {
returnvariable2 + 2
}
set (newValue){
}
}
}
let p1 = Person()
p1.variable1 = 12
打印的结果
before change variable2: 10
after change variable2: 30
原文链接:https://www.f2er.com/swift/323901.html