属性 getter 和 setter [英] Property getters and setters
问题描述
通过这个简单的类,我得到了编译器警告
With this simple class I am getting the compiler warning
试图在自己的 setter/getter 中修改/访问 x
Attempting to modify/access
x
within its own setter/getter
当我像这样使用它时:
var p: point = Point()
p.x = 12
我收到了 EXC_BAD_ACCESS.如果没有明确的支持 ivars,我该如何做到这一点?
I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?
class Point {
var x: Int {
set {
x = newValue * 2 //Error
}
get {
return x / 2 //Error
}
}
// ...
}
推荐答案
Setter 和 Getter 适用于 计算属性
;此类属性在实例中没有存储 - 来自 getter 的值旨在从其他实例属性计算.在您的情况下,没有要分配的 x
.
Setters and Getters apply to computed properties
; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x
to be assigned.
明确表示:如果没有明确的支持 ivars,我怎么能做到这一点".你不能 - 你需要东西来备份计算属性.试试这个:
Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:
class Point {
private var _x: Int = 0 // _x -> backingX
var x: Int {
set { _x = 2 * newValue }
get { return _x / 2 }
}
}
特别是在 Swift REPL 中:
Specifically, in the Swift REPL:
15> var pt = Point()
pt: Point = {
_x = 0
}
16> pt.x = 10
17> pt
$R3: Point = {
_x = 20
}
18> pt.x
$R4: Int = 10
这篇关于属性 getter 和 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!