/**
重写 属性观察器
1.只能给非lazy属性的变量存储属性设定属性观察器,不能给计算属性设定属性观察器。
属性观察器的限制:(1)不可以给只读的存储/计算属性,在子类中设定属性观察器,
(因为只读,不会改变嘛)
// 必须在父类中是可读可写的,才可以在子类中重写属性观察器啊。
*/
class Observer {
var storeProperty: Int = 0 {
willSet {
print("storeProperty father will Set")
}
didSet {
print("storeProperty father did Set")
}
}
var computeProperty: Int {
get {
return 0
}
set {
print("Do nothing!")
}
}
}
class ChildOfObserver: Observer {
override var storeProperty: Int {
willSet {
print("storeProperty will Set")
}
didSet {
print("storeProperty did Set")
}
}
override var computeProperty: Int {
willSet {
print("computeProperty will Set")
}
didSet {
print("computeProperty did Set")
}
}
}
let co = ChildOfObserver.init()
co.storeProperty = 10
/**
will Set
father will Set
father did Set
did Set
*/
co.computeProperty = 9
/**
computeProperty will Set
Do nothing!
computeProperty did Set
*/
原文链接:https://www.f2er.com/swift/322391.html