简体   繁体   English

将字典对象从Obj-C传递到Swift

[英]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: 在我的obj-C代码库中,我正在调用将NSDictionary对象传递给Swift类:

AppDelegate.m AppDelegate.m

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

SwiftClass.swift 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. 使用Xcode调试器,我在AppDelegate的setInfo方法上设置了一个断点,可以看到收到了推送通知。 But, once I step into the setInfo method, then the app crashes, never actually making it into the function. 但是,一旦我进入setInfo方法,应用程序就会崩溃,从不真正将其纳入函数中。 Thus, I suspect that the I'm not setting the parameters within setInfo properly. 因此,我怀疑我没有在setInfo中正确设置参数。

Is this an issue where I'm not passing in the Dictionary object in properly? 这是我没有正确传递Dictionary对象的问题吗?

NSDictionary can only be passed to swift as [NSObject: AnyObject] since an NSDictionary can contain objects of any type. NSDictionary只能作为[NSObject:AnyObject]传递给swift,因为NSDictionary可以包含任何类型的对象。 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 收到字典后,您可以检索键的值,并在需要时将该值转换为声明的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM