Swift 3 - 如何使用枚举原始值作为NSNotification.Name?

D. *_*reg 13 xcode enums nsnotificationcenter swift3

我正在使用Xcode 8 beta 5,我正试图设置这样的通知枚举

enum Notes: String {
  case note1
  case note2
}
Run Code Online (Sandbox Code Playgroud)

然后尝试将它们用作通知名称

NotificationCenter.default.post(name: Notes.note1.rawValue as NSNotification.Name,
                                object: nil, userInfo: userInfo)
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误.

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

有工作吗,还是我错过了什么?它适用于Xcode 7.3.1

任何帮助,将不胜感激.

小智 32

在这里,使用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)
    }
}
Run Code Online (Sandbox Code Playgroud)

其他方式

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Gau*_*ami 18

我这样做,对我来说这是管理通知名称的更简单方法.

Swift 3.0和Xcode 8.0

使用 Notification.Name的扩展,我们可以在其中定义静态名称,如下所示.

extension Notification.Name {
    static let newPasscodeSet = Notification.Name("newPasscodeSet")
    static let userLoggedIn = Notification.Name("userLoggedIn")
    static let notification3 = Notification.Name("notification3")
}
Run Code Online (Sandbox Code Playgroud)

我们可以使用这样的名字:

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

 func newPasscodeSetAction() {
     // Code Here.
 }
Run Code Online (Sandbox Code Playgroud)

希望这种简单的方式对您有所帮助.


OOP*_*Per 6

据我所知,NSNotification.NameXcode 7.3.1中捆绑的Swift 2.2.1/SDK中没有类型,所以我很好奇你是如何使它工作的.

无论如何,如果你想利用你的枚举,你需要写这样的东西:

NotificationCenter.default.post(name: NSNotification.Name(Notes.note1.rawValue),
                                object: nil, userInfo: userInfo)
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我最好定义你自己的建议Notification.Name是使用扩展来定义静态属性:

extension Notification.Name {
    static let note1 = NSNotification.Name("note1")
    static let note2 = NSNotification.Name("note2")
}
Run Code Online (Sandbox Code Playgroud)

(它比enum稍微长一点......,但是)你可以像这样使用它:

NotificationCenter.default.post(name: .note1,
                                object: nil, userInfo: userInfo)
Run Code Online (Sandbox Code Playgroud)