Lazy Property in Swift
Level 5354 keystrokes
Neither lazy property is created when ViewModel is initialized. Reading vm.data runs its closure, which prints Computing data... and then accesses loader, so DataLoader is created only at that point.
Swift code
1class DataLoader { // Prints a message when created, so we can see when it happens2 init() { print("DataLoader initialized") }3 func load() -> [String] {4 return ["item1", "item2", "item3"]5 }6}7 8class ViewModel { // Created on first access to loader9 lazy var loader = DataLoader() // A closure that is called once, on first access; lazy allows using self inside10 lazy var data: [String] = { // Printed before DataLoader exists11 print("Computing data...") // First access to loader: prints DataLoader initialized, then loads the items12 return self.loader.load()13 }()14}15 // Nothing is printed: both lazy properties are still uninitialized16let vm = ViewModel()17print("ViewModel created")18print("Accessing data...")// Triggers the chain: Computing data..., DataLoader initialized, then ["item1", "item2", "item3"]19print(vm.data)Output
ViewModel created Accessing data... Computing data... DataLoader initialized ["item1", "item2", "item3"]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
"× 14(× 11)× 11.× 9{× 5}× 5[× 3]× 3=× 3,× 2