Lazy readonly property in Swift

前端 未结 3 1901
深忆病人
深忆病人 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:33

    You can also use a private backing variable that initializes lazily:

    var foo : Int { return _foo }
    private lazy var _foo :Int = { return 42 }()
    
    0 讨论(0)
  • Its possible to do this with a computed property and a private struct. There is no need for the lazy keyword on the static var value, as assigning it the result of a block is implicitly lazy.

    var foo: Int {
        struct Holder {
            static var value = { return 42 }()
        }
        return Holder.value
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题