I want to use Lazy initialization for some of my properties in Swift. My current code looks like this:
lazy var fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
The thing is that once the fontSize is set it will NEVER change. So I wanted to do something like this:
lazy let fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
Which is impossible.
Only this works:
let fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
So - I want a property that will be lazy loaded but will never change.
What is the correct way to do that? using let
and forget about the lazy init? Or should I use lazy var
and forget about the constant nature of the property?
This is the latest scripture from the Xcode 6.3 Beta / Swift 1.2 release notes:
Evidently you were not the only person frustrated by this.
As dasblinkenlight points out lazy properties should always be declared as variables in Swift. However it is possible make the property read-only so it can only be mutated from within the source file that the Entity was defined in. This is the closest I can get to defining a "lazy let".
Swift book has the following note:
This makes sense in the context of implementing the language, because all constant stored properties are computed before initialization of an object has finished. It does not mean that the semantic of
let
could have been changed when it is used together withlazy
, but it has not been done, sovar
remains the only option withlazy
at this point.As far as the two choice that you presented go, I would decide between them based on efficiency:
var lazy
let
Note: I would further optimize your code to push the conditional into
CGFloat
initializer: