inessential by Brent Simmons

Adding a Notification Observer in Swift Using a Name Defined in Objective-C

I spent hours on this. This post exists for anybody Googling this particular problem.

Here’s the issue: I have a mixed Objective-C and Swift app.

I have a Swift class that needs to observe a Notification (aka NSNotification) posted in Objective-C code. The notification name is defined in a .h and .m file:

.h:

extern NSString *SomethingHappenedNotification;

.m:

NSString *SomethingHappenedNotification = @"SomethingHappenedNotification";

In Swift I tried a number of permutations, trying to get the notification name correct, including using Notification.Name​(rawValue: SomethingHappenedNotification) and similar. Each try resulted in a compile error.

The answer came from Tim Ekl (privately) and Jordan Rose (on Twitter) independently at the same time:

Ah, the word “Notification” is stripped from the name as redundant, so it becomes Notification .Name.Some (or just .Some).

In other words, the syntax for adding an observer looks like this:

NotificationCenter.default.addObserver(self, selector: #selector(someSelector(_:)), name: .SomethingHappened, object: nil)

Note that the Objective-C name SomethingHappenedNotification becomes just .SomethingHappened in Swift, and it’s automatically a Notification.Name.

It seems obvious now! But it wasn’t (at least for me). So: if I saved you some time today, then go be nice to somebody. :)