Swift – Useful NotificationName extension

Very often you should use a notification name in your code and every time you miss something, you write the wrong name and so on…

I want to simplify the coding like, so I use this solution. Easy and simple for me and I want to share:

We create an enum of notifications, like this for example:

enum Notifications: String, NotificationName {
    case <#YourNotificationName#>
    case kDoSomething
}

Next we extend this enum from a protocol called NotificationName with the “name” variable.

protocol NotificationName {
    var name: Notification.Name { get }
}

After this, we create an extension of the RawRepresentable class in order to create a new notification called as the enum raw value.

extension RawRepresentable where RawValue == String, Self: NotificationName {
    var name: Notification.Name {
        get {
            return Notification.Name(self.rawValue)
        }
    }
}

The code is complete.

To send the notifications without losing your head, you can use:

NotificationCenter.default.post(name: Notifications.kDoSomething.name, object: nil)

To observe (receive) a notifications instead, similar you can use:

NotificationCenter.default.addObserver(
     self, selector: #selector(doSomething()),
     name: Notifications.kDoSomething.name,
     object: nil)

Enjoy extensions!

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.