Swift 3 - How to use enum raw value as NSNotification.Name?

I am doing this way, For me this is more simple way to manage Notification names.

Swift 3.0 and Xcode 8.0

Using extension of Notification.Name, we can define static names inside that as following.

extension Notification.Name {
    static let newPasscodeSet = Notification.Name("newPasscodeSet")
    static let userLoggedIn = Notification.Name("userLoggedIn")
    static let notification3 = Notification.Name("notification3")
}

We can use that names like this:

 override func viewDidLoad() {
      NotificationCenter.default.addObserver(self, selector: #selector(self.newPasscodeSetAction), name: .newPasscodeSet, object: nil)
 }

 func newPasscodeSetAction() {
     // Code Here.
 }

Hope this simple way helpful for you.


Here you go, Use Swift 3 & Xcode 8.0

enum Notes: String {

    case note1 = "note1"
    case note2 = "note2"

    var notification : Notification.Name  {
        return Notification.Name(rawValue: self.rawValue )
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.post(name: Notes.note2.notification ,object: nil, userInfo: nil)
    }
}

Another way

import UIKit

extension Notification.Name
{
    enum MyNames
    {
        static let Hello = Notification.Name(rawValue: "HelloThere")
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.post(name: Notification.Name.MyNames.Hello ,object: nil, userInfo: nil)
    }
}