Lazy properties in Swift
The lazy
keyword in Swift allows you to delay the initialisation of a stored property until it is needed. The benefit of this approach can be an increase in performance as potentially expensive processes can be avoided during start up if they are not immediately required.
You can think of initialisation as assigning a variable with an initial value. An object can have properties, so when we initialise it, its properties are also initialised too.
Defining a lazy property
You define a lazy property by prefixing the var
keyword with lazy
. You cannot however use a constant as the value of lazy properties are calculated only after initialisation, whilst a constant needs to have a value.
As the purpose of using the lazy keyword is to delay execution of code until you initialise it, a simple self-executing closure is a perfect use case.
Let’s take the following pseudo code as an example
Imagine we have aMathsHelper
class which can be used to calculate the value of Pi and perhaps a collection of other random equations. We don’t need to calculate all the properties in this class if we only intend to use a subset of them. By prepending our var
with lazy
, we delay this until we need it.
Another advantage of this approach is that we now keep the declaration and setup of this property all in one place.
Can I declare a computed property as lazy?
Nope. A computed property is recalculated every time it is accessed however by definition a lazy property is calculated only once, when it is initialised.
Are there any downsides to this approach?
A var appended with the lazy keyword is not thread safe. This does not mean multiple threads will create multiple instances when attempting to access its value, rather if 2 or more threads attempt to access it at the same time, any thread after the first may receive a partially initialised instance of the object.
There is an open bug for addressing this behaviour within Swift itself.
tl:dr?
- The
lazy
keyword is used to delay initialisation of your variable - This can help increase performance and start up time
- This behaviour is not thread safe however
Feel free to leave any questions in the comments below :)