In chapter 25 you use a constant defined by a closure. Consequently you leave out the lazy keyword. If it had been a property the constant would have needed a value hence it would not have been lazily instantiated. Moving it to be a global makes me wonder if it is lazily instantiated?
@mikeneirinck Thanks very much for your question!
Are you referring to this block of code?
private let dateFormatter: DateFormatter = {
// the code that sets up the DateFormatter object
return formatter
}()
If so, because the code block is a let, it cannot be lazy. You get the following compile time error:
‘lazy’ cannot be used on a ‘let’
Here is an excerpt from The Swift Book which explains why:
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. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
I hope this helps!
All the best!
Sure but shouldn’t it be a lazy var?
This topic was automatically closed after 166 days. New replies are no longer allowed.