Swift: Beware of Computed Properties
Yesterday, I accidentally stumbled into yet another cool Swift feature: Computed Properties. I saw it used by someone else in their code, and found the syntax confusing enough at the time to think it did something different than it does!
A computed property is essentially a function disguised as a property. Here is an example:
var width = 100.0 var height = 100.0 // this is the computed property! var area: Double { return width * height } area // 10,000.0 width = 10.0 height = 10.0 area // 100.0 width = 15.0 height = 10.0 area // 150.0
In this example, area is used as a property, but it actually recalculates every single time it’s called, just like a function!
But think of what happens when the area is set. In the above case, you’ll actually get a compiler error saying you can’t set the area property (since it’s computed). But what if you still want to? You can actually split your computation between a getter and a setter:
var width = 100.0 var height = 100.0 // computing setter and getter var area: Double { get { return width * height } set(newArea) { let squareRootValue = sqrt(newArea) width = squareRootValue height = squareRootValue } } area // 10,000.0 area = 500 width // 22.36 height // 22.36 area = 100 width // 10.0 height // 10.0 area = 16 width // 4.0 height // 4.0
In this example, when the area is set, the width and height properties are re-calculated to be the square root of the new area.
If you do use a computed property, make sure you have a really good reason to do so, since some other class that calls the class with the computed property might not be aware of the recalculation happening and might not expect a different result!
I’m still trying to figure out good use cases for computed properties. I’d love to hear your thoughts in the comments.