SwiftMidMCQ
When should you use a computed property versus a method or a stored property?
Test your knowledge:
Explanation & Code
Answer: Use a computed property for a cheap, side-effect-free value derived from existing state; use a method for expensive work, side effects, or anything that needs arguments.
| Choose | When |
|---|---|
| Stored property | The value is its own state (not derivable), or caching an expensive result is worth the sync risk |
| Computed property | Derived from other state, O(1)-ish, no side effects, reads like an attribute (isEmpty, fullName) |
| Method | Expensive (O(n) or I/O), has side effects, may fail, or takes parameters (fetchUser(), distance(to:)) |
lazy var | Expensive, needed at most once, and the inputs never change afterwards |
Code Example:
struct Order {
var items: [Item]
var isEmpty: Bool { items.isEmpty } // ✅ cheap, derived
var itemCount: Int { items.count } // ✅ cheap, derived
func totalPrice(applying discount: Discount) -> Decimal { // ✅ method — takes input
items.reduce(0) { $0 + $1.price } * discount.multiplier
}
}
Key Points:
- Readers assume property access is fast — a computed property that hits disk or the network is a surprise.
- Caching a derived value in a stored property creates two sources of truth that can drift apart; prefer computed unless profiling says otherwise.
Rate your understanding: