Property Observer in Struct and Class
Property Observer Key point:
- It should be mutable i.e property Observer declared with var not let keyword.
- It monitoring the value of a property.
Let’s start with an example
Example 1.0 (class)

How many time didSet block get called?
Think for a time before start reading further.……🤔
A class is a reference type. So it can be mutable. It means whenever you changed the class property its update its value in the same memory location.
Let visualize by a diagram


As we have created the variable employee of Employee class. Here memory is allocated for employee variable i.e in location: 2047. which hold the value of the Employee structure base address i.e 2048. So whenever the value of employee variable changed, didSet block observer the changes
Output: It will print the didSet block 1 time.
Example 2 (Struct)
In Swift, a struct is a value type, not a reference type as a class. So struct is immutable.
It means whenever you changed the struct property a new struct object is created, the current object data is copied to the new one except for the changed property that will contain the new value set.
Let’s start with an example

How many time didSet block get called?
Think for a time before start reading further.……🤔
why the observer is called whenever you change a struct property?.🤔
Because when struct variable(i.e stud) is allocated. it points to its student structure base address i.e 2048. Whenever we modified the stud property system will create the new copy of student structure. And Eventually, a variable stud is holding an address of newly created student structure.
Hence variable stud value gets modified. So property Observer didSet is called each time.
Let’s visualize



Output: It will print the didSet block 3 times.
If you like this post, please share and give claps so others can find it 👏👏
You can follow me on Medium for updated articles. Also, connect with me on LinkedIn, Twitter.
If you have any comment, question, or recommendation, feel free to post them in the comment section below!👇