How do I convert an NSDictionary to a Swift Dictionary<String, NSObject>?
Decode your dictionary as Dictionary<String, NSObject>
instead of NSDictionary
.
let payload = aDecoder.decodeObjectOfClass(NSDictionary.self, forKey: "payload") as! Dictionary<String, NSObject>
Since you are using Cocoa Touch to serialize and deserialize, they are serialized as NSDictionary
, but you can cast it to a Swift Dictionary<,>
, as per WWDC 2014 Intermediary Swift and Advanced Swift videos.
You can also decode as NSDictionary
and then explicitly cast the object like so:
self.init(actionName: actionName, payload: payload as! Dictionary<String, NSObject>, timestamp: timestamp)
Basically, you are playing here with covariance/contravariance.
Are you sure that that's the correct declaration for init? The argument order is different than the one you're calling in your Objective-C code.
So, if you want a precise reimplementation, the last call should probably be self.init(actionName: actionName, timestamp: timestamp, payload: payload)
. Calling the initializer with the wrong order of arguments would result in exactly the error message you're getting.