Swift - 为什么惰性属性不能很容易地设为只读

Swift - why can't lazy properties be readily made read only

任何人都可以解释 neuburg 在 iOS 9 swift 基础知识书籍中关于惰性属性的评论 ...

"There are some minor holes in the language: lazy instance properties can’t have setter observers, and there’s no lazy let (so you can’t readily make a lazy instance property read-only)" .... 特别是没有 lazy let 防止只读的能力

来自苹果 documentation:

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.

但是,如果你想从 class/struct 中获取一个惰性值,并希望确保没有人可以写回该值,那么只需使用具有 return 值的函数。或者像 milos 说的那样——一个 private(set) on a lazy 属性。 (这不是一回事)所以不知何故一切皆有可能。 :)