Well , let me start of with an example :

Consider a scenario, where we have a Car that we drive everywhere (duh?) . Be it on a vacation, everyday work, grocery store, a new club that i overheard someone talking about ! Also, let us assume that with the rapid increase in technology, every car has an in-built GPS (though, not every car has one, JUST ASSUME).

Without lazy keyword

Our model is really simple, We have 2 classes for both GPS and Car. Since we have already assumed that every car would have an in-built GPS, class Car has a property gps .

Now, as soon as we reach the line:

let myVeryExpensiveCar = Car()

We will have the following output on the console :

GPS Initialized Car Initalized

… which , to be honest, is not rocket science !

What it depicts , is that, even when we have only created Car Object , GPS is initialised with it as well .

Let’s say we are travelling to work everyday, local grocery store every week, grandparents house ,say , often ; In all these cases, we don’t need GPS as we remember the route, even the alternate routes to get there, but with the above code, we will still be allocating memory to GPS variable even when we don’t need it. And we , as programmers, know the value of memory

Pic Credits: memegenerator.net

That’s where lazy comes into picture. What it does is, it will not be allocated memory until it is called the first time . To make a property lazy, just put the lazy keyword before the var declaration of that property (yup, you read it correct, var, not let as its initial value might not be retrieved until after instance initialization completes)

Now , the output will be :

Car Initalized

See, GPS is not initialised even though we have our Car up and running. Now as soon as we try to access gps property of our myVeryExpensiveCar instance:

myVeryExpensiveCar.gps

and hit run in the playground again, we will see the following added in console :

GPS Initialized

Pic Credits: makeameme.org

As soon as the compiler saw the lazy keyword, it skipped the initialisation and didn’t allocate memory to that variable. But , as soon as we tried to access the same variable, the first time, it was allocated memory at that very moment and after this point, it can be used a normal variable.