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

时间:2016-08-11 06:46:57

标签: xcode enums nsnotificationcenter swift3

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

enum Notes: String {
  case note1
  case note2
}

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

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

但我收到了错误。

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

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

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:32)

在这里,使用Swift 3& Xcode 8.0

WebView

另一种方式

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

答案 1 :(得分: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")
}

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

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

 func newPasscodeSetAction() {
     // Code Here.
 }

希望这种简单的方式对你有所帮助。

答案 2 :(得分:5)

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

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

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

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

extension Notification.Name {
    static let note1 = NSNotification.Name("note1")
    static let note2 = NSNotification.Name("note2")
}

(它比枚举有点长......,但是)你可以像这样使用它:

NotificationCenter.default.post(name: .note1,
                                object: nil, userInfo: userInfo)

答案 3 :(得分:1)

也许是快速4.2中的另一种方法

extension Notification.Name{
   struct RecordListNotification {
        static let recordListDidChange:Notification.Name = Notification.Name("recordListDidChange")
        static let recordListTimeDidChange = Notification.Name("recordListTimeDidChange")
    }
}

然后

NotificationCenter.default.post(name: Notification.Name.RecordListNotification.recordListTimeDidChange, object: nil)

还要避免冗长:

typealias RecordListNotification = Notification.Name.RecordListNotification

它可以使用:

NotificationCenter.default.post(name: RecordListNotification.recordListTimeDidChange, object: nil)