From the course: Practical Design Patterns in Swift

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Notifying observers

Notifying observers - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Notifying observers

- [Instructor] We're going to implement the observer pattern. I've gone ahead and created a single view playground. If you want to follow along with me, you can find the project in the exercise files folder, chapter 12, 12 two, begin. If we run the playground, it displays two buttons, and 10 labels. Hit Command + Option + Enter to display the live view if it's not visible. The UI button with the text Notify observers is the subject. And it should notify the UI label instances. When the user presses the Unregister observer button, it should detach an observer from the subject. Alright, let's get started. First, I create the observer protocol. Types will need to conform to this protocol if they want to be notified when the subject changes. Protocol Observer. Observer declares a single method, notify. I also add a property called UID. This let's us compare objects that implement the protocol when managing the observers. We are a UID of type Int. And it's a redundant property. Next comes…

Contents