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.

ChooseWhen
Stored propertyThe value is its own state (not derivable), or caching an expensive result is worth the sync risk
Computed propertyDerived from other state, O(1)-ish, no side effects, reads like an attribute (isEmpty, fullName)
MethodExpensive (O(n) or I/O), has side effects, may fail, or takes parameters (fetchUser(), distance(to:))
lazy varExpensive, 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:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.