如何在Swift中的通知中发送枚举值?

Mat*_*ler 6 enums nsnotificationcenter ios swift

我想在通知中发送枚举作为对象:

enum RuleError:String {
    case Create, Update, Delete
}

class myClass {

   func foo() {
       NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification", 
                                            object: RuleError.Create)
   }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用,因为枚举不匹配 AnyObject?.

知道如何规避这个问题吗?

Raf*_*fAl 7

object您正在使用的函数中的参数是发件人,发布通知的对象,而不是参数.在这里查看文档.

您应该将要发送的枚举值作为参数放在用户信息字典中,并使用以下方法:

func postNotificationName(_ aName: String,
                   object anObject: AnyObject?,
                 userInfo aUserInfo: [NSObject : AnyObject]?)
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

let userInfo = ["RuleError" : RuleError.Create.rawValue]

NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
        object: self,
        userInfo:userInfo)
Run Code Online (Sandbox Code Playgroud)

要处理通知,请先注册:

NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "handleRuleFailNotification:",
        name: "RuleFailNotification",
        object: nil)
Run Code Online (Sandbox Code Playgroud)

然后处理它:

func handleRuleFailNotification(notification: NSNotification) {

        let userInfo = notification.userInfo

        RuleError(rawValue: userInfo!["RuleError"] as! String)
    }
Run Code Online (Sandbox Code Playgroud)