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.titleHint 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.