Member-only story
Computed Properties in Swift
This post is going to explain what a computed property is and how to use it.
There is a Swift Playground with examples in this post. It can be found at this link. Feel free to copy the files or clone the entire repo, but the repo has more than just this post’s sample code.
Topics covered in this post
- What is a Computed Property
- Examples using getters and Setters
- Why use a Computed Property
What is a Computed Property?
A computed property is similar to a stored property, except a computed property does not hold a value. A computed property’s value is calculated based on the provided getter defined for the property when the computed property is called.
A computed property can also affect other properties in the class, struct, or enumeration by using a setter.
Important Things about Computed Properties
- Always declare computed properties as a variable,
var
. A computed property is never declared as a constant,let
, since the values are never fixed. - The code inside the getter runs every time the property is called.
- Setters can affect other properties
- When declaring a computed property, a type has to be specified