BadmintonCat BadmintonCat - 2 months ago 7
Swift Question

Are Swift constants lazy by default?

Something I still not quite understand about Swift ... let's say I want a property that instantiates a class in a base class used for several sub classes, e.g. ...

let horse = Horse();


Is
horse
instantiated right after app/class initialisation or when the property is accessed for the first time?

On the other hand using
lazy var
guarantees that the property is only instantiated the first time it is accessed ...

lazy var horse = Horse()


But then
horse
is not a constant. So in this case if I access
horse
multiple times I would get multiple instances of
horse
created, right?

What if I wanted both, a lazy property that is also a constant?

Answer

Not exactly. Say you have a class Farm and inside Farm there is horse property.

class Farm {
    let horse = Horse()
}

In this case horse property is initialized when class instance initialized. If you make it lazy you have to make it mutable to.

class Farm {
    lazy var horse = Horse()
}

In this case horse property is initialized when it is accessed first time. And later when it is accessed again it returns same instance again instead of reinitialize it. But since it is mutable property you can assign new instance of Horse to it. After you assign it new value it will return this new value whenever it is accessed.

EDIT: If let horse = Horse() is defined in global space then it is lazily created at first access.

Comments