Why is 'didset' called on a property when I set the property of that property?

后端 未结 2 507
感动是毒
感动是毒 2021-01-11 18:03

In this code when the text changes, titleEditingChanged is called (as expected). But when it executes the line

investment?.title = sender.text!         


        
2条回答
  •  無奈伤痛
    2021-01-11 18:04

    It is called because Investment is probably a struct, not a class. In Swift structs are value types, not reference types as classes. So, structs are not "mutable in place".

    It means that whenever you change a struct property a new struct object is allocated to replace the current one, the current object data is copied to the new one except for the changed property that will contain the new value set.

    Remember that the compiler does not let you change a struct property whenever you initialize a struct object with a let command (with a class you can do it).

    That explains why the observer is called whenever you change a struct property. Once a new struct object is allocated to replace the current one, it will now be stored in another memory block, so its value will be changed and the didSet observer will be called.

    PS: It will not happen if you define Investment as a class instead of a struct.

提交回复
热议问题