SwiftJuniorMCQ
What is the difference between a stored property and a computed property?
Test your knowledge:
Explanation & Code
Answer: A stored property keeps a value in the instance's memory, while a computed property stores nothing and calculates its value every time it is read.
- Stored —
letorvar, part of the instance's layout. Available on structs and classes (not enums). - Computed — always
var, defined by aget(and optionalset). Available on structs, classes, and enums, and can be added in extensions.
Code Example:
struct Rectangle {
// Stored — takes up memory in every Rectangle
var width: Double
var height: Double
// Computed — derived on every access, nothing stored
var area: Double {
width * height
}
}
var rect = Rectangle(width: 4, height: 5)
print(rect.area) // 20.0
rect.width = 10
print(rect.area) // 50.0 — always in sync with its inputs
Key Points:
- Extensions can add computed properties but cannot add stored properties.
- A computed property can never fall out of sync with the values it derives from — that is the main reason to prefer it over caching a derived value in a stored property.
- Callers expect property access to be cheap. If the work is expensive, use a method (
func calculateArea()) or cache the result in alazy/ stored property instead.
Rate your understanding: