Lazy keyword in Swift

minna zacharias
2 min readMay 31, 2021

Swift has a mechanism built right into the language that enables just-in-time calculation of expensive work, and it is called a lazy variable.

A lazy property might be lesser known to beginners in Swift but are actually super valuable once you know when and how to use them. There are a few important things to learn so you know when to use which type of property

So the first question you might have is, “I’ve never seen this keyword before.

What does lazy do?

Well, you know how there’s some people who if they need to get to work at 9:00, they’ll wake up at 6:00.

You know, they’ll spend half an hour doing yoga or some crazy stuff like that, and then do a whole bunch

of prep work, eat a proper breakfast. And those people are not lazy. But then there’s another category

of people, myself included, which, you know, most people would categorize as lazy, and they’re the sort of

person who if you need to be out the door by 8:30, you’re probably wake up around 8:20, and try

to get everything done in 10 minutes, just so that you can have that extra hour of peaceful sleep.

So this is kind of similar to what lazy variables are. When we create a variable that we declare is lazy,

then it only gets loaded up with a value at the time point when it’s needed, i.e., when you tried to use

this thing called lazy variable that is when all of this code is going to run, and it’s going to

have a value set.

So whereas the lazy person gets a lying benefit, the lazy variable gets a memory benefit.

So you’re only occupying the memory when it’s needed, rather than having everything set up beforehand.

As lazy properties are only calculated once called it means it will also use the state of the moment it’s getting called.

The lazy variables are mutable.The lazy property is marked as lazy var. You can't make it lazy let because lazy properties must always be variables.

--

--