Stored, computed and lazy properties

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

How many times do 'building' and 'computing' print?

final class Report {
    lazy var summary: String = {
        print("building"); return "S"
    }()
    var title: String { print("computing"); return "T" }
}
let r = Report()
_ = r.summary; _ = r.summary
_ = r.title; _ = r.title
Options
Hint 1 of 1

Which one stores its result?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B building 1, computing 2

Correct. Lazy runs once; computed runs on every read.

Why not the others?
  • A building 2, computing 2. A lazy property stores its value after the first access.
  • C building 1, computing 1. Computed properties aren't cached.
  • D building 0, computing 2. The first read of summary triggers the initializer.

30-second answer

A stored property keeps a value in the instance. A computed property has no storage; it runs its getter on every access. A lazy var is stored but initialized on first access, then reused. Use lazy for expensive setup that may never be needed; use computed for values derived from other state.

Practise saying it · 30 s. No recording, just a timer

Explain stored vs computed vs lazy.

Say your answer out loud, then check which of these points you covered:

  • Stored keeps a value
  • Computed runs every time
  • Lazy runs once on first access

Deep dive

lazy must be var and isn't thread-safe: two threads may initialize it twice.

Lazy properties can reference self in their initializer.

Structs with lazy properties need var instances, because first access mutates.

Computed properties can have a setter that updates other stored state.

Common mistakes

  • Doing expensive work in a computed property read in a loop.
  • Using lazy for state shared across threads.

Senior take & follow-ups

Seniors mention lazy's thread-safety caveat and that static let is lazily and safely initialized.

Follow-up questions

Think of your answer first, then open the hint.

  1. Is lazy initialization thread-safe?

    Show hint

    No; use a lock or a static let, which is thread-safe.

  2. Can a let be lazy?

    Show hint

    No.

Suggest a fix if something here is wrong or out of date.