Sometimes you want to execute some code in Swift 3 whenever a variable changes its value. And perhaps you’ve done this previously by creating a function that you call whenever it makes sense in your code.

However, there’s a MUCH better way!

We’ll learn how to use observers which act like watchdogs – they bark whenever even the tiniest part of a variable changes!

Declare a variable and implement the didSet function:

 

There are also other functions you can override in there, such as willSet, called BEFORE the variable is actually changed:

 

You can even stack these:

Of course there are many more functions you can override so I dare you to go look for them 😉

 

How to Observe Changes in Variables with Swift 4 and iOS 12
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share This

Exhausted by your 9 - 5?

Would you prefer to work for half the time and earn double? The first step to your freedom is understanding how apps make money. Simply enter your email below and I will send you a free PDF describing the process.

If you're serious about improving your life then do not miss this opportunity.


You have subscribed! Please check your email to confirm this subscription and to receive your item!