Lazy readonly property in Swift

前端 未结 3 1916
深忆病人
深忆病人 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 }()
    

提交回复
热议问题