[swift-evolution] [Pitch] Make NSNotification names a protocol like ErrorProtocol

Kenny Leung kenny_leung at pobox.com
Wed Jun 29 18:55:51 CDT 2016


Hi All.

While converting to Swift3, my biggest hurdle was figuring out what to do with a custom NSNotification. In Objective-C, it’s a plain NSString, and the same in Swift2.

I assumed in Swift3 that it worked like ErrorProtocol and errors as enums, but as it turns out, you need to create a custom instance of Notification.Name(“MyNotificationName”). This does not seem very Swifty, and I think it would work better if there was a NotificationNameProtocol and you could create enums with String raw values.

Magically, a string seems to compile in one area of the API, but not another:

// This compiles with either a string or instance of Notification.Name for name:
        NotificationCenter.default().addObserver(self, selector: #selector(Self._contextDidSave(notification:)), name: "blah", object: managedObjectContext)

// This will only compile with an instance of Notification.Name:
                NotificationCenter.default().post(name: SomeNotificationObject, object: self)

-Kenny



More information about the swift-evolution mailing list