Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: why aren't all variables lazy by default?

Tags:

swift

In comparing these two options for defining an instance property:

var networkManager = NetworkManager.sharedInstance()

var lazy networkManager = NetworkManager.sharedInstance()

Both:

  • Can evaluate a block to get the value
  • Can be declared inline (not a block, like above)

Lazy:

  • Can refer to self
  • Is not calculated until needed
  • If you don't use it, it is never calculated

Non-lazy:

  • No benefits whatsoever

It appears that there is no benefit to ever use a non-lazy variable. So why does the language allow the programmer to make this inferior choice?

(I am NOT asking about the difference between var and let à la Are Swift constants lazy by default?)

like image 365
William Entriken Avatar asked Jan 17 '16 18:01

William Entriken


People also ask

Are static properties lazy in Swift?

Static properties are also implicitly lazy, in that they're only computed once they're accessed for the first time. We can also attach observers to any stored property, which enables us to run code each time that a value was (or will be) assigned to that property.

Why we use lazy VAR in Swift?

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. These variables are created using a function you specify only when that variable is first requested.

How does swift define lazy property?

You indicate a lazy stored property by writing the lazy modifier before its declaration. You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes.

What is lazy initialization in Swift?

lazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.


1 Answers

One reason might be that lazyness is not well-suited for situations where you want control when the evaluation happens. this is relevant in cases where the work being done in the assignment has side effects.

Although this pertains to closure, this blog post by stuart sierra explains this idea very well, and I think it applies equally in any language.

like image 91
leeor Avatar answered Oct 03 '22 15:10

leeor