11.6 Swift重写属性观察器
/** 重写 属性观察器 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 */ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |