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

Kenny Leung kenny_leung at pobox.com
Wed Jun 29 20:07:54 CDT 2016

Yes, this is the solution that I’m using, but:

1. I think following the pattern of ErrorProtocol would be better

2. It doesn’t explain why I can use String in one instance and not the other when they are both typed the same:

// Can use String or Notification.Name
    @nonobjc final public func addObserver(_ observer: AnyObject, selector aSelector: Selector, name aName: Name, object anObject: AnyObject?)
// Can only use Notification.Name
    public func post(name aName: NSNotification.Name, object anObject: AnyObject?)


> On Jun 29, 2016, at 5:11 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>> 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.
> The migrator constructs the Notification.Name instances at the call site, but I believe the *actual* intent is that you should assign them to a constant—either one in your own type:
> 	// Old
> 	let MyClassWillFooNotificationName = "MyClassWillFoo"
> 	// New:
> 	class MyClass: … {
> 		static let WillFoo = Notification.Name("MyClass.WillFoo")
> 	}
> Or in an extension to `Notification.Name` itself.
> -- 
> Brent Royal-Gordon
> Architechies

More information about the swift-evolution mailing list