Browse Questions
- 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.
- An actor is a reference type that protects its mutable state from concurrent access.
- To create a custom Xcode File Template from scratch, create a .xctemplate directory inside ~/Library/Developer/Xcode/Templates/File Templates/<Category>/, add a TemplateInfo.plist declaring the…
- UIViewPropertyAnimator is an object that owns an animation, which makes that animation interruptible, reversible, and scrubbable.
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.