Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy readonly property in Swift

Tags:

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?

like image 490
MBulli Avatar asked Sep 25 '14 21:09

MBulli


People also ask

What is lazy property in Swift?

A lazy stored property is a property whose initial value isn't calculated until the first time it's used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

How do I make a property readonly in Swift?

If you have a property in Swift that needs to be weak or lazy , you can still make it readonly by using private(set) .

What is private set Swift?

Apr 22, 2022. swift ios. I recently discovered Swift feature where setter for class and struct properties could be set to private while getter is internal or publicly accessed. This allows us to expose properties to the outside world without worrying if someone is going to change them in the future.


1 Answers

If readonly and private are synonyms for you in this specific case, then you can make the setter private by explicitly declaring it:

private(set) lazy var foo : Int = { return 42 }() 

That's a good compromise between immutability and laziness.

like image 195
Antonio Avatar answered Sep 20 '22 13:09

Antonio