[swift-corelibs-dev] Foundation Renaming Question

Brent Royal-Gordon brent at architechies.com
Sun Jul 3 10:18:22 CDT 2016


> In the past bare strings were acceptable for postNotificationName and addObserverForName.  Yet now constructing a Notification and Notification.Name seem to be a bit unwieldy.  Example:
> 
> let ConnectedNotification    = Notification(name:Notification.Name(rawValue:"ConnectedNotification"))
> 
> That seems to be quite convoluted and I'm not sure why there isn't a convenience init that allows for
> 
> let ConnectedNotification    = Notification(name:"ConnectedNotification")

You're running into trouble because you're not following the typical pattern for these types. The intended usage is:

* You assign the Notification.Name to a constant.

	class ChatConnection {
		static let didConnect = Notification.Name("ChatConnection.didConnect")
		…
	}

* You create Notification instances on demand, or preferably let the NotificationCenter make them for you.

	extension ChatConnection {
		func connectionCompleted() {
			NotificationCenter.default().post(name: ChatConnection.didConnect, object: self)
		}
	}

Individual Notifications are meant to be one-off instances. If you follow this pattern, you'll find that the API design suddenly makes a lot more sense!

-- 
Brent Royal-Gordon
Architechies



More information about the swift-corelibs-dev mailing list