通过这个简单的类,我得到了编译器警告
试图在自己的setter/getter中修改/访问x
当我这样使用它时:
var p: point = Point()
p.x = 12
我得到一个EXC_BAD_ACCESS。我怎么能做到这一点没有显式支持变量?
class Point {
var x: Int {
set {
x = newValue * 2 //Error
}
get {
return x / 2 //Error
}
}
// ...
}
更新:Swift 4
在下面的类setter和getter应用于变量sideLength
class Triangle: {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) { //initializer method
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get { // getter
return 3.0 * sideLength
}
set(newValue) { //setter
sideLength = newValue / 4.0
}
}
创建对象
var triangle = Triangle(sideLength: 3.9, name: "a triangle")
Getter
print(triangle.perimeter) // invoking getter
把
triangle.perimeter = 9.9 // invoking setter
详细解释一下GoZoner的回答:
这里真正的问题是递归地调用getter。
var x:Int
{
set
{
x = newValue * 2 // This isn't a problem
}
get {
return x / 2 // Here is your real issue, you are recursively calling
// your x property's getter
}
}
就像上面的代码注释建议的那样,你无限地调用x属性的getter,它将继续执行,直到你得到一个EXC_BAD_ACCESS代码(你可以在你的Xcode的游乐场环境的右下角看到旋转器)。
请看Swift文档中的例子:
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
注意,center computed属性在变量的声明中从不修改或返回自身。