我的问题是如何处理属性方法的继承,例如 set
、get
、didSet
、willSet
,...?
举个例子:我想重写 Swift 类中属性的 setter 方法。这是我想要实现的目标(这显然不起作用):
class A {
var value: Int {get {...} set {...} }
}
class B: A {
var value: Int {
set(newValue) {
// do some fancy stuff...
}
}
}
这也不起作用:
// in class B
override func setValue(newValue: Int) {
// do some fancy stuff...
}
我们可以在 Swift 中做这样的事情:
class A {
var _value: Int = 0
var value: Int {
get {
return _value
}
set {
_value = newValue
}
}
}
class B: A {
override var value: Int {
get {
return _value
}
set {
_value = newValue + 1
}
}
}
let a = A()
a.value = 1
print(a.value) // => 1
let b = B()
b.value = 1
print(b.value) // => 2
这种方法不是很优雅,因为我还必须实现 getter 方法,这实际上是没有必要的,因为只有 setter 应该被重写。
最佳答案
你可以这样做:
class A {
var value: Int = 0
}
class B: A {
override var value: Int {
get { return super.value }
set {
// Something fancy...
super.value = newValue
}
}
}
虽然您仍然需要在 B
中实现 getter,但至少不需要 _value
,这有助于保持类 A
的干净.
关于swift - Swift 中属性方法(set、get、didSet、willSet 等)的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436030/