Swift Language Design Patterns - Creational Observer


The observer pattern is where an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern.Wikipedia reference

Basically the observer pattern is used when you have an object which can notify observers of certain behaviors or state changes.

First lets create a global reference (outside of a class) for the Notification Centre :

let notifCentre = NotificationCenter.default

Great now we can call this from anywhere. We would then want to register a class as an observer...

notifCentre.addObserver(self, selector: #selector(self.myFunc), name: "myNotification", object: nil)

This adds the class as an observer for "readForMyFunc". It also indicates that the function myFunc should be called when that notification is received. This function should be written in the same class:

func myFunc(){
    print("The notification has been received")

One of the advantages to this pattern is that you can add many classes as observers and thus perform many actions after one notification.

The notification can now simply be sent(or posted if you prefer) from almost anywhere in the code with the line:

notifCentre.post(name: "myNotification", object: nil)

You can also pass information with the notification as a Dictionary

let myInfo = "pass this on"
notifCentre.post(name: "myNotification", object: ["moreInfo":myInfo])

But then you need to add a notification to your function:

func myFunc(_ notification: Notification){
    let userInfo = (notification as NSNotification).userInfo as! [String: AnyObject]
    let passedInfo = userInfo["moreInfo"]
    print("The notification \(moreInfo) has been received")
    //prints - The notification pass this on has been received