Codementor Events

Property Observers in swift

Published May 01, 2020

Property observers in swift are like other observers available in iOS app development that notify user on some condition happening. With property observers, a block of code gets called when property values changes. Property observers allows property to observe and respond when a its value has been changed/updated. Thus will gets called every time property value gets changed.

Types of property observers

WillSet gets called before the value is stored to property, while didSet gets called immediately after the new value is stored to property

We have two types of property observers in swift

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. We added willSet and didSet observers to our transactions property. Its same like, we add get and set method to properties in swift.

willSet property observer has default value associated with name “newValue”. 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 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 where some thing you need to trigger 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 load our transactions UITableView(We are assuming that user can delete a transaction entry too and also update it)

Discover and read more posts from Aman Aggarwal
get started
post commentsBe the first to share your opinion
Show more replies