Property Observers in swift

Property observers in swift are somewhat like any other observers available in iOS SDK. In iOS app development, observers are the objects that notify user on a particular event. With property observers, a block of code gets called when property values changes. Property observers provides developer a handy way to monitor changes to the property. And respond when its value has been changed/updated. Thus providing developer an opportunity to track any changes to a property. So that they can react according to the property value and do some logic as per new value assigned to property.

Types of property observers

We have two types of property observers in swift

  • willSet
  • didSet

First one is, WillSet that gets called before the value is stored to a property, and second one is didSet that gets called immediately after the new value is stored to a property

Watch video on YouTube

https://youtu.be/ea4ilXpYlPo

Syntax for property observers

 var transactions = [Float]() {
        willSet{
            print("New value == \(newValue)")
        }
        
        didSet {
            print("Old value = \(oldValue)")
        }
    }

Here in above syntax, we have a property transactions of type Float array. We added willSet and didSet observers to our transactions property. Its same like same as, we add get and set method to properties in swift.

willSet property observer has default value associated with name “newValue” and didSet property observer has default value associated with name “oldValue”. Though you can rename those values name as shown below

var transactions = [Price]() {
        willSet(willSetValue){
            print("New value == \(willSetValue)")
        }
        
        didSet(didSetValue) {
            print("Old value = \(didSetValue)")
        }
    }

Where to use property observers

Now you have learned about how to write property observers in swift. Question arises where we should use them. As property observer, observe and respond to change in property value. The ideal scenario to use them, in case you need do to some logic or need to do user interface change whenever there is a change in property value.

If we take example of our transactions property, so we will use didSet observer of it to re-load our transactions UITableView(We are assuming that user can delete a transaction entry too and also update it)

Read Next Article

https://iostutorialjunction.com/2020/04/how-to-create-custom-uiview-class-with-xib-in-swift-tutorial.html