Swift Lazy Properties
A lazy property is a stored property whose starting value is built only when the property is first read. Later reads reuse the value that was built.
An index built on first read
The made line prints before the building line, which proves the index was not built when the notebook was created. The second read prints the index again with no second building line.
class Notebook {
lazy var index: String = {
print("Building index")
return "a, b, c"
}()
}
let book = Notebook()
print("Notebook made")
print(book.index)
print(book.index)A file list loaded once
Opening the archive prints its line without loading anything. The first read of files loads the list, and the second read reuses that same list.
class Archive {
lazy var files: [String] = {
print("Loading files")
return ["notes", "photos"]
}()
}
let archive = Archive()
print("Archive opened")
print(archive.files.count)
print(archive.files)A value that is never built
This program reads only the title of the report. No building line appears, because the chart property is never read.
class Report {
var title = "Weekly"
lazy var chart: String = {
print("Building chart")
return "Chart data"
}()
}
let report = Report()
print(report.title)Example
struct Backpack {
lazy var packingList: [String] = {
print("Packing list built")
return ["rope", "lamp"]
}()
}
var pack = Backpack()
print("Backpack bought")
print(pack.packingList)
print(pack.packingList.count)Key points
- The lazy mark delays building the starting value until the first read.
- The building code runs once at most for each value.
- A lazy property is declared with var and never with let.
- A value holding a lazy property in a struct is declared with var.
- Later reads return the stored value without building it again.
In this example, the Backpack struct holds a lazy packing list, and the bought line prints before any building line. The first read of packingList builds the list and prints Packing list built, then shows the list itself. The last read prints the count 2 with no second building line, so the list was built only once.
Note
A lazy property that is never read is never built.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When is the starting value of a lazy property built?