如下代码:
class Father {
static var someProperty = 2
class var secondProperty: Int {
return 3
}
}
class Son : Father {
override static var someProperty: Int { // error
set {
_ = newValue + 2
}
get {
return super.someProperty
}
}
override class var secondProperty: Int { // error
willSet {
// code...
}
didSet {
// code...
}
}
}
上述代码有误,不过官方文档中注明了以下内容:
“You can override an inherited instance or type property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 3)”。 iBooks.
比如想要给父类的某个类型属性添加属性观察器,监听值的变化,该如何实现?或者说,如何操作才能在子类中重写父类的类型属性以及给类型属性添加属性观察器?
Adding observers to parent class properties is very simple, just
override
需要观察的父类属性,然后就可以添加willSet
或者didSet
.But it seems that it is not possible to override the class attributes of the parent class. I will try it again and add it later.