Search code examples
swiftpropertieslazy-initialization

Whats the difference of using ={}() with a lazy property or just =


There are two different ways of using the lazy property syntax and I fail to see the difference between them:

//1
lazy var a = { "hello" }()

//2
lazy var b = "hello"

In other words, why would or wouldn't you use {}() Is there a difference between them or is it just different looks for doing the same thing?


Solution

  • There isn't much difference. lazy doesn't care whether you initialise the property with a closure or not. lazy just makes the property lazily initialised, i.e. the initialisation expression (the part after the =) is evaluated on the first access of the property. That expression can be anything: a string literal, or an immediately-invoked closure, or whatever you like.

    So the difference here is just the difference between evaluating "foo" and { "foo" }(). The former is just a string literal, whereas the latter invokes a closure, and that closure returns the same string. So it's a tiny bit of overhead, that will totally be optimised away if you use -O. Using Godbolt.org, you can verify that the assembly output are the same when using -O: String literal | Closure