Lazy Property in Swift

Level 4291 keystrokes

A lazy property is created on first access, not when the object is initialized. DataLoader is created during the first showData() call, so Loading data... appears only once, after Accessing loader.

Swift code

1class DataLoader {
// Prints a message when an instance is created
2 init() { print("Loading data...") }
3 var data = "Loaded Data"
4}
5
6class ViewController {
// lazy: DataLoader() runs on the first access to loader, not in init
7 lazy var loader = DataLoader()
8
9 func showData() {
10 print("Accessing loader")
// The first call creates the loader here; later calls reuse it
11 print(loader.data)
12 }
13}
14
// No DataLoader yet, so nothing is printed
15let vc = ViewController()
16print("ViewController created")
// Prints Accessing loader, Loading data..., Loaded Data
17vc.showData()
// Loader already exists: only Accessing loader and Loaded Data
18vc.showData()

Output

ViewController created
Accessing loader
Loading data...
Loaded Data
Accessing loader
Loaded Data
Practice typing this code

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.

  • (× 10
  • )× 10
  • "× 8
  • .× 6
  • {× 4
  • }× 4
  • =× 3

More Swift examples at level 4

← Swift typing practice