加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

11.6 Swift重写属性观察器

发布时间:2020-12-14 06:31:42 所属栏目:百科 来源:网络整理
导读:/** 重写 属性观察器 1. 只能给非 lazy 属性的变量存储属性设定属性观察器,不能给计算属性设定属性观察器。 属性观察器的限制:( 1 )不可以给只读的存储 / 计算属性,在子类中设定属性观察器, (因为只读,不会改变嘛) // 必须在父类中是可读可写的,才

/**

重写 属性观察器

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

*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读