1

I have been searching on why lazy, computed property, and property observer can not be (let) constant, I know for example lazy are not assigned until it is accessed, but why it can not be (let), does that mean lazy will be holding a nil value or whatever value before it's being accessed and assigned to the value we assigned? please explain the same thing for computed property, and property observer.

Zouhair Sassi
  • 1,403
  • 1
  • 13
  • 30
Zyz
  • 123
  • 1
  • 9
  • you can easily test when it will have a value, just put a `print` inside the `lazy` block. It won't get triggered until you access the value. Before that the value is not even `nil`. It's not ever defined. For more see [here](https://stackoverflow.com/questions/31515805/difference-between-computed-property-and-property-set-with-closure/50845853#50845853) – mfaani Nov 07 '19 at 11:58

2 Answers2

3

Lazy properties : 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.

computed property : whereas computed properties calculate (rather than store) a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

property observer : property observers is to monitor changes in a property’s value, if you define it let then how you can monitor changes because let is one type of constant which you can not change after init.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
SGDev
  • 2,256
  • 2
  • 13
  • 29
0

Rules:-

  1. You can declare a property with either let or var keyword.
  2. In swift, let variable must be initialized before the owner of the let variable is initialized.
  3. Once you assign a value to the let variable, you can't change its value again.

Now let's see all three types of properties one by one:-

  1. lazy variable - It initializes after the owner is initialized. So, rule 2 violates here.
  2. computed variable - Whenever you access a computed variable, it returns the value after some calculation/operation. So, rule 3 violates here.
  3. property observer - didSet or willSet of property observer gets called when you change its value. So, rule 3 violates here.
ranjit.x.singh
  • 307
  • 4
  • 9