Property Observers in swift

In this article, we will look into property observers. According to Apple’s documentation:

Property observers observe and respond to changes in a property’s value, called every time a property’s value is set, even if the new value is the same as the property’s current value .

lazy var name = "John"
print("My name is \(name)")

Why Use Property Observers?

The need for property observers arises when you have to keep a track on a property to determine when the value changes in order to perform some logic. So, instead of having some functions that checks the value of the property to perform some action, you can abstract that into the willSet and have it perform the logic when the value is set to the value you want.

You can add property observers in the following places:

  • Stored properties that you define
  • Stored properties that you inherit
  • Computed properties that you inherit

You have the option to define either or both of these observers on a property:

  • willSet is called just before the value is stored.
  • didSet is called immediately after the new value is stored.

If you implement a willSet observer, it’s passed the new property value as a constant parameter. You can specify a name for this parameter as part of your willSet implementation.

    var totalSteps: Int = 0{
        willSet(newTotalSteps){
            print(newTotalSteps)
        }
    }

If you don’t write the parameter name and parentheses within your implementation, the parameter is made available with a default parameter name of newValue.

    var totalSteps: Int = 0{
        willSet{
            print(newValue)
        }
    }

Similarly, if you implement a didSet observer, it’s passed a constant parameter containing the old property value. You can name the parameter or use the default parameter name of oldValue.

    var totalSteps: Int = 0{
        didSet{
            print(oldValue)
        }
    }

If you assign a value to a property within its own didSet observer, the new value that you assign replaces the one that was just set.

var totalSteps: Int = 0{
    didSet{
        totalSteps = 20
    }
}

totalSteps = 30
print(totalSteps) // this will print 20

totalSteps = 40
print(totalSteps) // this will print 20(because we assign value in didSet thus updated value replaced with assigned value in didSet)

The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They aren’t called while a class is setting its own properties, before the superclass initializer has been called.

I will cover this in detail in next article

Let’s Understand the Property Observers

The willSet and didSet observers for totalSteps are called whenever the property is assigned a new value. This is true even if the new value is the same as the current value.

This example’s willSet observer uses a custom parameter name of newTotalSteps for the upcoming new value. In this example, it simply prints out the value that’s about to be set.

The didSet observer is called after the value of totalSteps is updated. It simply print the oldValue. In another example we set the value in didSet In result, the new value that you assign replaces the one that was just set in didSet.

Points that you should remember when Use Property Observers

  • Property observers are declared as a variable and not as constants because it is only a mutable property that can be tracked by property observers. Hence, observers are declared with var and not the let keyword.
  • One thing to note is that willSet and didSet will never get called on setting the initial value of the property. It will only get called whenever you set the property by assigning a new value to it. It will always get called even if you assign the same value to it multiple times.
  • Property observers cannot be used on lazy variable because lazy variable get properly initialised and assigned to memory only when they are called in your program.
  • A property with observers on it when declared should have initial value assigned to it. This actually makes the difference between computed properties and property observers. Computed properties returns a value computed from other variable or properties and does not store the value in memory. Hence, to place observers on a property, you need to set the property to an initial value of a particular type. This value could be optional type or any other type(We will discuss this in detail in next article).
  • willSet and didSet both have the default parameters newValue and oldValue. You are free to choose a custom parameter name of your choice as shown in the code above. These parameters are constants, hence you cannot mutate their values. Also note that in didSet, you can access the oldValue parameter and also the property whose value is already set.

In-out Parameter

If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called. This is because of the copy-in copy-out memory model for in-out parameters: The value is always written back to the property at the end of the function. For a detailed discussion of the behavior of in-out parameters, see In-Out Parameters.

Note: In this article we discussed how can we use property observers in stored properties and in next article we will discuss for computed property and incase of inheritance.

Final Thought

I believe you now have a better understanding of how property observers in Swift works after reading through this article. Thanks for reading and feel free to raise any comment or questions below and I will have them answered.

Thank you very much for your precious time.

Hope you guys enjoy it.

Let me know your thoughts in the comment section.

Extend your knowledge

The Twitter contact:

Any questions? You can get in touch with me here

4 thoughts on “Property Observers in Swift”

Leave a Reply

Your email address will not be published.