Property getters and setters

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

Leave a Comment