gpt4 book ai didi

swift - Swift中属性方法(set、get、didSet、willSet等)的继承

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:00 24 4
gpt4 key购买 nike

我的问题是如何处理setgetdidSetwillSet等属性方法的继承, ...?

举个例子:我想覆盖 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com