Video
What are Computed Properties?
Computed properties are properties that do not actually store a value. Instead, they allow you to supply a getter and an optional setter to define its behavior.
A computed property is a read-only computed property when it is only supplied with a getter, but not a setter.
Getters
Think of a getter as a function that runs when you call when you want to retrieve the value of the computed property.
In this example, an area
computed property is declared. This provides an easier way to access the area of the Rectangle
.
This can also be achieved with a function, without a computed property, however, the computed property provides a more convenient and readable way to access the Rectangle
's area.
Shorthand Getters
If the computed property only has a getter, you can omit the get {}
clause and directly return the value. This can help make code shorter and easier to read.
If there is only one line within a getter, like functions, you can use an implicit return and omit the return
keyword.
Adding Setters
You can also define a setter on the computed property. Think of this like a function you can supply the computed property to handle when a user sets the value.
In the example below, the radians
computed property's setter is used to update the degrees
property. This allows you to set the value from both the degrees
and radians
property.
Shorthand Setters
You do not need to supply a parameter name for the setter's new value. You can take advantage of the default newValue
.
Computed Properties & SwiftUI
SwiftUI uses computed properties to compose a View in the body
computed property.
You can also define your own computed properties as part of your SwiftUI views.
In this example, the searchResults
computed property is able to filter the fruits
array with the searchQuery
. This makes it easier to access the filtered results.
When defining a computed property, it should not be a State variable. In the example above, when the searchQuery
is updated, the searchResults
computed property is automatically updated and the relevant views are re-rendered.