Lazy readonly property in Swift

前端 未结 3 1900
深忆病人
深忆病人 2021-01-01 13:00

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.

3条回答
  •  一生所求
    2021-01-01 13:56

    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.

提交回复
热议问题