Property Observer in Struct and Class

Shantaram Kokate
3 min readApr 9, 2019

--

Property Observer Key point:

  1. It should be mutable i.e property Observer declared with var not let keyword.
  2. 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

Struct 1.0
Struct 1.1
Struct 1.3

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!👇

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response