Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift Cookbook

You're reading from   Swift Cookbook Proven recipes for developing robust iOS applications with Swift 5.9

Arrow left icon
Product type Paperback
Published in Jun 2024
Publisher Packt
ISBN-13 9781803239583
Length 422 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (4):
Arrow left icon
Chris Barker Chris Barker
Author Profile Icon Chris Barker
Chris Barker
Daniel Bolella Daniel Bolella
Author Profile Icon Daniel Bolella
Daniel Bolella
Nathan Lawlor Nathan Lawlor
Author Profile Icon Nathan Lawlor
Nathan Lawlor
Keith Moon Keith Moon
Author Profile Icon Keith Moon
Keith Moon
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Swift Fundamentals 2. Chapter 2: Mastering the Building Blocks FREE CHAPTER 3. Chapter 3: Data Wrangling with Swift 4. Chapter 4: Generics, Operators, and Nested Types 5. Chapter 5: Beyond the Standard Library 6. Chapter 6: Understanding Concurrency in Swift 7. Chapter 7: Building iOS Apps with UIKit 8. Chapter 8: Building iOS Apps with SwiftUI 9. Chapter 9: Getting to Grips with Combine 10. Chapter 10: Using CoreML and Vision in Swift 11. Chapter 11: Immersive Swift with ARKit and Augmented Reality 12. Chapter 12: Visualizing Data with Swift Charts 13. Index 14. Other Books You May Enjoy

Getting property changing notifications using property observers

It’s common to want to know when a property’s value changes. Perhaps you want to update the value of another property or update some UI element. In Objective-C, this was often accomplished by writing your own getter and setter or using Key-Value Observing (KVO). However, in Swift, we have native support for property observers.

Getting ready

To examine property observers, we should create an object with a property that we want to observe. Let’s create an object that manages users and a property that holds the current user’s name.

Enter the following code into a new playground:

class UserManager {
 var currentUserName: String = "Emmanuel Goldstein"
}

We want to present some friendly messages when the current user changes. We’ll use property observers to do this.

How to do it...

Let’s get started:

  1. Amend the currentUserName property definition so that it looks as follows:
    class UserManager {
     var currentUserName: String = "Guybrush Threepwood" {
      willSet (newUserName) {
       print("Goodbye to \(currentUserName)")
       print("I hear \(newUserName) is on their way!")
      }
      didSet (oldUserName) {
       print("Welcome to \(currentUserName)")
       print("I miss \(oldUserName) already!")
      }
     }
    }
  2. Create an instance of UserManager, and change the current username. This will generate friendly messages:
    let manager = UserManager()
    manager.currentUserName = "Elaine Marley"
    // Goodbye to Guybrush Threepwood
    // I hear Elaine Marley is on their way!
    // Welcome to Elaine Marley
    // I miss Guybrush Threepwood already!
    manager.currentUserName = "Ghost Pirare LeChuck"
    // Goodbye to Elaine Marley
    // I hear Ghost Pirare LeChuck is on their way!
    // Welcome to Ghost Pirare LeChuck
    // I miss Elaine Marley already!

How it works...

Property observers can be added within curly brackets after the property declaration, and there are two types – willSet and didSet.

The willSet observer will be called before the property is set and provides the value that will be set on the property. This new value can be given a name within brackets – for example, newUserName:

willSet (newUserName) {
 //...
}

The didSet observer will be called after the property is set and provides the value that the property had before being set. This old value can be given a name within brackets – for example, oldUserName:

didSet (oldUserName) {
 //...
}

There’s more...

The new value and old value that are passed into the property observers have implicit names, so there is no need to explicitly name them. The willSet observer is passed a value with an implicit name of newValue, and the didSet observer is passed a value with an implicit name of oldValue.

Therefore, we can remove our explicit names and use the implicit value names:

class UserManager {
 var currentUserName: String = "Guybrush Threepwood" {
  willSet {
   print("Goodbye to \(currentUserName)")
   print("I hear \(newValue) is on their way!")
  }
  didSet {
   print("Welcome to \(currentUserName)")
   print("I miss \(oldValue) already!")
  }
 }
}

See also

Further information about property observers can be found in Apple’s documentation on the Swift language at http://swiftbook.link/docs/properties.

You have been reading a chapter from
Swift Cookbook - Third Edition
Published in: Jun 2024
Publisher: Packt
ISBN-13: 9781803239583
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime