Historically, in Objective-C, properties were implemented through access methods (getters and setters). In Swift, a special syntactical construct for computed properties was introduced, allowing for easy creation of properties that calculate their value "on the fly". This enhances encapsulation and expressiveness of the type's code.
Problem: It is not always convenient to store the result as a stored property, especially if the value depends on other properties or changes constantly. Using calculation methods creates a less readable interface for the type, hiding its nature.
Solution: A computed property is defined using get and, if necessary, set. Every time such a property is accessed, a computation is performed rather than reading from memory. This allows, for example, the construction of derived properties that are automatically synchronized with the object's other state.
Example code:
struct Rectangle { var width: Double var height: Double var area: Double { get { return width * height } set { // Automatically update width to the new value of area (example) width = sqrt(newValue / height) } } } var rect = Rectangle(width: 5, height: 2) print(rect.area) // 10 rect.area = 36 print(rect.width) // 3.0
Key features:
Can you use willSet/didSet with a computed property?
No, willSet and didSet apply only to stored properties. For computed properties, these observers do not work because there is no automatic storage of the value.
Can a computed property have a weak or implicitly unwrapped type?
Yes, a computed property can be optional or implicitly unwrapped. However, it makes no sense to make such properties weak, as they do not hold a reference — only a computation.
In which cases is it better to use private set in a computed property?
The access modifier private(set) cannot be applied to a computed property with both get and set, only to a stored property. For a computed property, the set can be completely private using private set, but this is implemented implicitly through the accessibility of the set block.
public var area: Double { private set { ... } get { ... } }
The getter of a computed property fetches large data from the network each time it is accessed, causing freezes and network overload.
Pros:
Cons:
The computed property calculates the final value based on other stored properties with minimal costs; caching of heavy logic is moved to a separate mechanism.
Pros:
Cons: