Custom Notifications in Swift

Notifications allow an object of one class to send a message for an object of another class to handle so the two classes don’t have to know about each other. The Cocoa framework has dozens of notifications, but you can also create your own.

Using custom notifications involves the following steps:

Get the notification center

Post the notification

Observe the notification

Handle the notification

Getting the Notification Center

The notification center is where you post and observe notifications. Each Cocoa application has its own notification center. Use the NotificationCenter class’s default property to access your application’s notification center.

let center = NotificationCenter.default

Posting a Notification

Call the NotificationCenter class’s post function to post a notification. Supply the name of the notification and an optional object if you need to pass data to the notification observer.

Handling a Notification

Handling a notification involves writing a function. Functions that handle notifications take a NSNotification object as an argument.

func handleNotification(_ note: NSNotification) {
}

The argument for the function must match the argument for the selector when observing the notification. I put the _ character before the note argument so I wouldn’t have to supply an argument to the selector. If I didn’t have the _ character, I would have to supply the note argument to the selector when observing the notification.