Global variables are always computed lazily?

The Swift Programming Language book says:

Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier.
Local constants and variables are never computed lazily.

I don't quite understand what does it mean. I made a test:

var a = print("A")
print("B")
var b = a

If they were lazy, I would expect it to print B and then A, but it prints A and then B. How is it lazy?

1 Like

You executed your test in a main.swift or a playground. Those settings behave more like a function body, and hence fall under this:

Local constants and variables are never computed lazily.

If you move the first line to a separate file, it will print “B” before “A”. If you then change the last line to var b = (), it will never print “A” at all.

3 Likes

Thanks a lot, that's what I supposed. I indeed used Playground environment and I thought that can be the difference in this case. :sweat_smile:

I would just add that lazy initialization does not guarantee execution order. It's legal for a global to be initialized at any time between program launch and the variable's first use. Fortunately main.swift behaves predictably like a playground or repl in this respect.

1 Like