In Objective-C, a custom notification is just a plain NSString, but it\'s not obvious in the WWDC version of Swift 3 just what it should be.
You can add a custom initializer to NSNotification.Name
extension NSNotification.Name {
enum Notifications: String {
case foo, bar
}
init(_ value: Notifications) {
self = NSNotification.Name(value.rawValue)
}
}
Usage:
NotificationCenter.default.post(name: Notification.Name(.foo), object: nil)
if you use string-only custom notifications, there's no reason to extend any classes but String
extension String {
var notificationName : Notification.Name{
return Notification.Name.init(self)
}
}
I may suggest another option which is similar to what @CesarVarela suggested.
extension Notification.Name {
static var notificationName: Notification.Name {
return .init("notificationName")
}
}
This will let you post and subscribe on notifications easily.
NotificationCenter.default.post(Notification(name: .notificationName))
Hope this will help you.
NSNotification.Name(rawValue: "myNotificationName")
You could also use a protocol for this
protocol NotificationName {
var name: Notification.Name { get }
}
extension RawRepresentable where RawValue == String, Self: NotificationName {
var name: Notification.Name {
get {
return Notification.Name(self.rawValue)
}
}
}
And then define your notification names as an enum
anywhere you want. For example:
class MyClass {
enum Notifications: String, NotificationName {
case myNotification
}
}
And use it like
NotificationCenter.default.post(name: Notifications.myNotification.name, object: nil)
This way the notification names will be decoupled from the Foundation Notification.Name
. And you will only have to modify your protocol in case the implementation for Notification.Name
changes.
There is a cleaner (I think) way to achieve it
extension Notification.Name {
static let onSelectedSkin = Notification.Name("on-selected-skin")
}
And then you can use it like this
NotificationCenter.default.post(name: .onSelectedSkin, object: selectedSkin)