RyJ
RyJ

Reputation: 4025

Initialize only when needed

I have a method that gets called occasionally. It relies on a property that I don't want to instantiate unless that method is called, but at the same time I don't want to reinstantiate the property if it is already instantiated. Is this what lazy loading is for?

I'm currently using:

property = property ?? Property()

and that seems to be working fine, but I want to do a sanity check on this approach.

Upvotes: 2

Views: 64

Answers (1)

diatrevolo
diatrevolo

Reputation: 2822

All you have to do is declare the property as lazy, and it will only be initialized when needed.

class MyClass {
  lazy var myLazyArray = [String]()
}

var myObject = MyClass() // myObject.myLazyArray still not initialized
myObject.myLazyArray.append("hello") // Now we're in business!
print(myObject.myLazyArray)

Upvotes: 3

Related Questions