One feature we have not yet discussed is the concept of lazy properties. Marking a property as lazy allows Swift to wait to initialize it until the first time it is accessed. This can be useful in at least a few important ways.
The most obvious way to use lazy properties is to avoid unnecessary memory usage. Let's look at a very simple example first:
struct MyType { lazy var largeString = "Some String" } let instance = MyType()
Even though we created a new instance of MyType
in the preceding code, largeString
is not set until we try to access it. This is great if we have a large variable that may not be needed on every instance. Until it is accessed, it is not taking up any memory.