#39: Lazy Variables
Question
// Swift Quiz
— objc.io (@objcio) November 20, 2019
class X {
lazy var a: Int? = {
print("A")
return nil
}()
func b() -> Int? {
print("B")
return a ?? 3
}
let c: () -> Int = {
print("C")
return 5
}
}
let x = X()
x.b() ?? x.c()
// What prints?
Solution
Solution: BA
— objc.io (@objcio) November 21, 2019
When `x.b()` is called, "B" gets printed.
Within `b`, `a` is accessed, which executes the code in the closure of the lazy stored property, printing "A".
Since `b` returns a non-`nil` value, `c` is never called.https://t.co/s7500CWmAg