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

D. Greg picture D. Greg · Aug 11, 2016 · Viewed 13.1k times · Source

I'm using Xcode 8 beta 5 and I'm trying to setup an enum of notifications like this

enum Notes: String {
  case note1
  case note2
}

Then trying to use them as the notification names

NotificationCenter.default.post(name: Notes.note1.rawValue as NSNotification.Name,
                                object: nil, userInfo: userInfo)

But I'm getting an error.

Cannot convert value of type 'String' to specified type 'NSNotification.Name'

Is there a work around, or am I missing something? It works in Xcode 7.3.1

Any help would be appreciated.

Answer

user6375148 picture user6375148 · Aug 11, 2016

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)
    }
}