How I use notifications in swift

Today while I was converting one of my easier projects from objective-c to swift I researched the best way of using  (custom)notifications in swift. Below is the method I selected.

The class that is sending the notifications

Embedding notification strings

I like to embed the literal strings for the notifications inside the class that is sending them. Since swift does not (yet) support static variables in classes itself I selected the method where I embed a struct “notify” inside the class that contains the static and constant (let) strings. Yes, structs can have static variables classed not… a bit weird maybe…

Sending the notification

Sending the notification boils down to calling the postNotificationName… function and retrieving the correct name from the “notif” struct

The class that is listening for notifications

Hook the listeners

I implement a function “hookListeners” that groups all the addObserver statements.
In the above code, the class that want to listen to notifications is derived from UIViewController so I call this function in the viewWillAppear. I am sure that there are other points that are possible as well (viewDidLoad, viewDidAppear) but this works for me.

Notice the elegant way I can access the name for the notification!

The selector in the addObserver function  is specified as a literal string. This means that the compiler does not do any checking whether its a valid selector (compared to objective-c this is a step backwards in my opinion). Make sure that the selector does not point to a private function if so this will throw an “unrecognised selector send to…” runtime crash

Unhook te listeners

Same principle here, one function “unhookListeners” and called in viewWillDisappear.

How I use notifications in swift