07-19-2023, 01:27 AM
While playing a little bit with Swift I tried to write a readonly and lazy initialized property. I quickly wrote that line of code just to learn that it's not allowed.
// no valid Swift code.
lazy let foo : Int = { return 42 }()
You have to declare lazy properties as `var`.
The swift book clearly states that let with lazy is not possible for a good reason:
> “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.”
Supposing I would like to have a readonly lazy property in swift. What's the best way to archive that?
// no valid Swift code.
lazy let foo : Int = { return 42 }()
You have to declare lazy properties as `var`.
The swift book clearly states that let with lazy is not possible for a good reason:
> “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.”
Supposing I would like to have a readonly lazy property in swift. What's the best way to archive that?