Vee Vee - 6 months ago 23
iOS Question

Passing a Dictionary object from Obj-C to Swift

In my obj-C code base, I'm calling passing a NSDictionary object to a Swift class:

AppDelegate.m

-(void)application:(UIApplication *) application didReceiveRemoteNotification: (NSDictionary *)dictionaryInfo {
...
[[SwiftClass sharedInfo] setInfo:dictionaryInfo];
...
}


SwiftClass.swift

class SwiftClass: NSObject {

static let sharedInfo = MYQNotificationInfo()

func setInfo(notification:Dictionary<String,String>) -> Void {
// runtime error happens before this line
}


}

The app compiles but when I receive a push notification, it crashes. Using Xcode debugger, I set a breakpoint at the setInfo method within AppDelegate and can see that the push notification is received. But, once I step into the setInfo method, then the app crashes, never actually making it into the function. Thus, I suspect that the I'm not setting the parameters within setInfo properly.

Is this an issue where I'm not passing in the Dictionary object in properly?

Answer

NSDictionary can only be passed to swift as [NSObject: AnyObject] since an NSDictionary can contain objects of any type. Try this:

func setInfo(notification:Dictionary<NSObject,AnyObject>) -> Void {

}

Once you receive the dictionary you can retreive a value for a key and downcast that value to it's declared type when needed