Lazy properties

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.

Avoiding unnecessary memory usage

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.

Avoiding unnecessary processing

We can also take this idea of a lazy property even further using a closure to calculate the value:

class Directory {
    lazy var subFolders: [Directory] = {
        var loaded = [Directory]()
        // Load subfolders into 'loaded'
        return loaded
    }()
}

Here we are actually making use of a self-evaluating closure. We did this by adding the open and close parentheses to the end of the closure. By doing this, we are assigning the subFolders property to the result of executing the closure; because it is a lazy property, the closure will not be executed until the subFolders property is accessed for the first time. Just like the plain lazy property that can help us avoid taking up unnecessary memory, this technique allows us to avoid running time-consuming operations when we don't have to.

Localizing logic to the concerned property

An alternative to using lazy properties to achieve our goals above would be to use optional properties instead and simply assign those values later as needed. This is an OK solution, especially if our only goal is to reduce unnecessary memory usage or processing. However, there is one other great benefit to the lazy property solution. It produces more legible code by connecting the logic to calculate a property's value right by its definition. If we simply had an optional property it would have to be initialized in either an initializer or by some other method. It would not be immediately clear when looking at the property what its value will be and when it will be set, if it will be set at all.

This is a critically important advantage as your code base grows in size and age. It is very easy to get lost in a code base, even if it is your own. The more straight lines you can draw from one piece of logic to another, the easier it will be able to find the logic you are looking for when you come back to your code base later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset