Tim
Tim

Reputation: 667

swift 4 post notification userInfo with mixed types (string and NSMutableArray)

I just started learning swift today. Im trying to post a notification that has both [String, String] data and [String, NSMutableArray] data. I get an error that says:

Cannot convert value of type 'NSMutableDictionary' to expected argument type [AnyHashable : Any]?

Ive tried to find a solution or similar code but have not been able to understand the problem yet. Can someone tell me what the real problem is? I suspect is has something to do with mixing my dictionary value types. If so, how is this done in swift?

        var dict = NSMutableDictionary()
        dict["status"] = "ok"
        var list = NSMutableArray()
        list.add("this")
        list.add("is")
        list.add("a test")
        dict["list"] = list

        NotificationCenter.default.post(name: Notification.Name("testing"), object: nil, userInfo: dict) <--- error

error points to the 'dict' variable in the post notification line

Thank you

Upvotes: 0

Views: 3659

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185681

You can't use NSMutableDictionary as the userInfo type. Nor should you be using that (there's precious few reasons to use NSMutableDictionary or NSMutableArray in Swift). Say var dict: [String: Any] = [:] instead (or let dict = […]). Similarly, list should be type as [String] rather than NSMutableArray.

let dict = ["status": "ok",
            "list": ["this", "is", "a test"]]
NotificationCenter.default.post(name: Notification.Name("testing"), object: nil, userInfo: dict)

Upvotes: 1

Related Questions