Friday, January 23, 2015

Let’s Build Swift Notifications

Mike Ash:

NSNotifications are both simple and powerful, which is why they show up so often in the frameworks. Specifically, they have a few distinct advantages:

  1. Loose coupling between notification senders and receivers.
  2. Support for multiple receivers for a single notification.
  3. Support for custom data on the notification using the userInfo property.

There are some disadvantages as well:

  1. Sending and registering for notifications involves interacting with a singleton instance with no clear relationship to your classes.
  2. It’s not always clear what notifications are available for a particular class.
  3. For notifications which use userInfo, it’s not always clear what keys are available in the dictionary.
  4. 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.
  5. Removing a notification registration requires an explicit removal call.
  6. 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.

Comments RSS · Twitter

Leave a Comment