Running Turtle
Running Turtle

Reputation: 12752

Correct use of lazy instantiation

My understanding of lazy instantiation is that it should be used in cases where

And yet, I come more and more across code like this [pseudo code]:

class SomeClass {
    lazy var itemSize: CGSize = { return CGSize(width: 80, height: 80) }()

    ....
    init() {
        [use itemSize for some init work]
    }
}

To me, this does not make sense since itemSize will always need to be initialized, is not expensive and does not depend on any unknown property. Am I missing something ?

Upvotes: 3

Views: 156

Answers (2)

matt
matt

Reputation: 534958

Actually you've omitted (or elided into your third bullet point) the most common reason for lazy instance properties: they can refer, explicitly or implicitly, to self, whereas normal instance properties cannot.

Another point: lazy instance properties do not have to be define-and-call anonymous functions, and in the silly example you give, there is no reason whatever for it to be so. This would have done just as well:

lazy var itemSize: CGSize = CGSize(width: 80, height: 80) 

Both lazy and define-and-call are useful, and are often useful together, but don't confuse them.

Upvotes: 1

Fogmeister
Fogmeister

Reputation: 77631

You are absolutely correct.

In that particular case there is no need for lazy instantiation.

The cases that you stated are also correct.

However, there shouldn't be any huge detrimental effect of using lazy instantiation in this case.

But, if I'd seen it like that I would have changed it to a let and remove the lazy. (Especially if it isn't being mutated at any point).

Upvotes: 3

Related Questions