Search code examples
swiftnsnotificationcenternsnotificationsnsnotificationswift3

How do you create custom notifications in Swift 3?


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.


Solution

  • 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.