Browse Questions
Answer:
Declare a var with a get block that returns the value and a set block that updates the underlying stored state. The setter receives the incoming value, named newValue by default.
Code Example:
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get {
celsius * 9 / 5 + 32
}
set(newFahrenheit) { // explicit parameter name
celsius = (newFahrenheit - 32) * 5 / 9
}
}
var kelvin: Double {
get { celsius + 273.15 }
set { celsius = newValue - 273.15 } // shorthand: implicit `newValue`
}
}
var t = Temperature(celsius: 0)
t.fahrenheit = 212
print(t.celsius) // 100.0
Key Points:
- Shorthand setter — omit the parameter name and use
newValue. - Shorthand getter — if the getter is a single expression, the
returnis implicit (Swift 5.1+). - A computed property cannot be setter-only;
setalways requires aget. - On a struct, the setter is implicitly
mutating, so it can only be called on avarinstance.