Matthieu Riegler Matthieu Riegler - 6 months ago 23
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() {
object: RuleError.Create)

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

Any idea how to circumvent this problem ?


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]

        object: self,

And to handle the notification, first register for it:

        selector: "handleRuleFailNotification:",
        name: "RuleFailNotification",
        object: nil)

Then handle it:

func handleRuleFailNotification(notification: NSNotification) {

        let userInfo = notification.userInfo

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