Property getters and setters

Atomix picture Atomix · Jun 3, 2014 · Viewed 254.4k times · Source

With this simple class I am getting the compiler warning

Attempting to modify/access x within its own setter/getter

and when I use it like this:

var p: point = Point()
p.x = 12

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
        }
    }
    // ...
}

Answer

GoZoner picture GoZoner · Jun 3, 2014

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.

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 }
  }
}

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