Howdy.
I've been building (on Linux) the latest off of master for Swift and the
accompanying swift-corelibs-foundation. I can see where the great renaming
is in full swing and have been updating my code accordingly.
One area where I'm a bit confused is with the new API for
NotificationCenter and Notification.
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")
Then, the APIs for post and observe seem to be mismatched:
NotificationCenter.defaultCenter().postNotification(ConnectedNotification)
vs.
NotificationCenter.defaultCenter().addObserverForName(ConnectedNotification.name)
I would think an addObserverForNotification would be more appropriate here.
Finally, combining topics a bit, but they are related:
let ConnectedNotification =
Notification(name:Notification.Name(rawValue:"ConnectedNotification"))
let DisconnectedNotification =
Notification(name:Notification.Name(rawValue:"DisconnectedNotification"))
These notifications are for the same API, so I'm assuming I'm "doing this
wrong" and that the more Swifty way would be too put these in a struct or
enum, so I'm curious as to what folks recommend.
Thanks!
···
--
Joseph Bell
@iachievedit
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