Lazy var in Swift

Payal Kandlur
2 min readDec 14, 2021

--

As a developer, memory management will always be the first priority. Your application must run smoothly without any hindrance. Swift has this beautiful mechanism that enables the just-in-time calculation of huge tasks, using the lazy keyword.

In simple terms, suppose you want to get some work done only when it's required, and not all the time, provided the work once done for the very first time, is never done again since it's already done.

This is exactly what lazy does for you, it will not compute the variable unless called and once it is called for the very first time it computes and stores the value for future uses.

To be more precise, Apple's documentation says:

A lazy stored property is a property whose initial value isn’t calculated until the first time it’s used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

And also not to forget this important line from the documentation:

You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore can’t be declared as lazy.

Let's go ahead with a simple example:

struct Address {
var city: String?
var state: String?
lazy var welcome = {
return "Welcome to \(city), \(state)"
}()
}
var mumbai = Address(city: "Mumbai", state: "Maharashtra")print(mumbai.welcome)

Run this on your playground and check for the output. You will see the line in the lazy var closure being executed!

This is a very simple example but if the computation is a heavy calculation of a number of loops the usage of lazy is essential since it will be calculated just once on the initialization and this improves the performance of your app.

Lazy stored properties are computed only the first time they are needed after which it saves the value and on the second call it just uses the saved value. And this makes it different from the computed property.

The pitfall of the lazy property:

Lazy property is not thread-safe since it is not initialized and loaded into the memory when it’s declared and defined.

As mentioned in the documentation:

If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property hasn’t yet been initialized, there’s no guarantee that the property will be initialized only once.

That's all!😊 If you find this helpful do share and drop in your thoughts in the comment section.

--

--

No responses yet