Lazy initialization (also sometimes called lazy instantiation, or lazy loading) is a technique for delaying the creation of an object or some other expensive process until it’s needed. When programming for iOS, this is helpful to make sure you utilize only the memory you need when you need it.
This technique is so helpful, in fact, that Swift added direct support for it with the
To understand why this is useful, let’s first go over the old way of creating lazy properties.
The Old Objective-C Way
In Objective-C, if you had a mutable array property you wanted lazily initialized, you’d have to write this:
To people new to Objective-C, this presents a few different learning curves. First of all, you need to know that the method name has to exactly match the property name. If you misspelled the method name, this would silently fail and
players would be nil when you tried to access it.
You also need to know the
_players instance variable was created for you automatically when your property was synthesized. Before Xcode 4.4, you had to manually synthesize your variable using the
@synthesize keyword, like so:
@synthesize players; // - or - @synthesize players = _players;
Which would tell you that the instance variable used for the players property is
_players. Nowadays Xcode handles synthesizing your properties for you. If you didn’t know that, then using the underscore before the property name might not be immediately obvious.
The Swift Way
Now in Swift, this can all be simplified down to one line:
lazy var players = [String]()
Keep in mind you do need to declare your lazy property using the
var keyword, not the
let keyword, because constants must always have a value before initialization completes.
If you wanted to add logic to your lazy initialization, Swift makes this easy by letting you define a closure after your lazy property:
If you prefer, you can also lazily initiate your property using an instance method:
Or a class method:
But people will most likely prefer using the new closure mechanic, as it keeps the logic near the property declaration.
When should I use lazy initialization?
One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized.
For example, if you have a Person class and a
personalizedGreeting property. The
personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person. Here’s a quick example:
Note: This example originally had
unowned self to prevent a strong reference cycle but this is not necessary. An immediately-applied closure (the above
@noescape, and does not retain the captured
self. More on this can be found in this discussion.
When you initialize a person, their personal greeting hasn’t been created yet:
let person = Person(name: "John Doe") // person.personalizedGreeting is nil
But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:
NSLog(person.personalizedGreeting) // personalizedGreeting is calculated when used // and now contains the value "Hello, John Doe!"
Another good time to use lazy initialization is when the initial value for a property is computationally intensive.
For example, if you have an object that performs some really intense algorithm to determine the number of faces in a picture, make the
numberOfFaces property lazily initialized.
Or if you had a class that calculates several different large numbers, you would want to make sure they’re only calculated on-demand:
Direct support for lazy property initialization is just one of the many great features of Swift. In the next few months, I’ll cover more great features and shortcuts. Stay tuned!
Updated 7/23/14: Updated to reflect the
@lazy attribute being changed to
lazy. Also updated to the new Array declaration syntax.
Updated 8/24/18: Updated to remove
unowned self, which is not necessary. More information can be found in this discussion
How to personalize your command line with Prezto.
Finding the right design pattern to fit your architecture is the first step in ensuring quality.