Matthieu Riegler Matthieu Riegler - 5 months ago 19
iOS Question

How to send an enum value in a notification in Swift?

I want to send an enum as an object in a notification :

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

class myClass {

func foo() {
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
object: RuleError.Create)
}
}


Unfortunately this doesn't work since an enum does not match
AnyObject?
.

Any idea how to circumvent this problem ?

Answer

The object parameter in the function you're using is the sender, the object posting the notification, not the parameter. Check out the docs here.

You should put the enum value you want to send as a parameter in the user info dictionary and use the following method:

func postNotificationName(_ aName: String,
                   object anObject: AnyObject?,
                 userInfo aUserInfo: [NSObject : AnyObject]?)

In your case:

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

NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
        object: self,
        userInfo:userInfo)

And to handle the notification, first register for it:

NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "handleRuleFailNotification:",
        name: "RuleFailNotification",
        object: nil)

Then handle it:

func handleRuleFailNotification(notification: NSNotification) {

        let userInfo = notification.userInfo

        RuleError(rawValue: userInfo!["RuleError"] as! String)
    }