Let’s Build Swift Notifications
NSNotifications are both simple and powerful, which is why they show up so often in the frameworks. Specifically, they have a few distinct advantages:
- Loose coupling between notification senders and receivers.
- Support for multiple receivers for a single notification.
- Support for custom data on the notification using the
userInfo
property.There are some disadvantages as well:
- Sending and registering for notifications involves interacting with a singleton instance with no clear relationship to your classes.
- It’s not always clear what notifications are available for a particular class.
- For notifications which use
userInfo
, it’s not always clear what keys are available in the dictionary.userInfo
keys are dynamically typed and require cooperation between the sender and receiver that can’t be expressed in the language, and messy boxing/unboxing for non-object types.- Removing a notification registration requires an explicit removal call.
- It’s difficult to inspect which objects are registered for any given notification, which can make it hard to debug.
My goal in reimagining notifications in Swift is to remedy these problems.
He runs into an interesting case where casting is necessary to satisfy Swift’s type system. I didn’t expect this, and it’s instructive to think about what is going on here. Also note how it transparently handles observer functions with different numbers of parameters.