in swift 3, now they give us a new better way to define getter and setter, that’s really nice when you have whole bunch of variables there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// example code from the iOS 10 course by Mark Price, highly recommended!
class TipCalc {
private var _billAmount = 0.0
private var _tipPercent = 0.0
private var _tipAmount = 0.0
private var _totalAmount = 0.0
//
var tipAmount: Double {
return _tipAmount
}
// this will be a read-only computed attribute,
// you can even use dot(.) to access the value
//
var billAmount: Double {
get {
return _billAmount
} set {
_billAmount = newValue
}
}
}

the variable newValue inside the setter was default given naming by swift, even it was an instance variable of a struct, check the following example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)
}
}
}