如何将NSDictionary转换为Swift字典< String,NSObject> ;? [英] How do I convert an NSDictionary to a Swift Dictionary<String, NSObject>?
问题描述
我在Swift中重写一个Objective-C类,以获得对语言的感觉。在Objective-C我的类包括以下方法:
I am rewriting an Objective-C class in Swift to get a feel for the language. In Objective-C my class included the following method:
- (id) initWithCoder:(NSCoder *)aDecoder
{
return [self initWithActionName:[aDecoder decodeObjectOfClass:[NSString class] forKey:@"actionName"]
payload:[aDecoder decodeObjectOfClass:[NSDictionary class] forKey:@"payload"]
timestamp:[aDecoder decodeObjectOfClass:[NSDate class] forKey:@"timestamp"]];
}
在编译器尝试和错误之后,我设法重写它:
After some trial and error with the compiler, I managed to rewrite it like this:
convenience init(aDecoder: NSCoder) {
let actionName = aDecoder.decodeObjectOfClass(NSString.self, forKey: "actionName") as NSString
let payload = aDecoder.decodeObjectOfClass(NSDictionary.self, forKey: "payload") as NSDictionary
let timestamp = aDecoder.decodeObjectOfClass(NSDate.self, forKey: "timestamp") as NSDate
self.init(actionName: actionName, payload: payload, timestamp: timestamp)
}
b $ b
但是,这仍然给我最后一行的错误:找不到重载 init
,接受提供的参数。方法签名 init
是
However, this still gives me an error on the last line: "Could not find an overload for init
that accepts the supplied arguments." The method signature of init
is
init(actionName: String, payload: Dictionary<String, NSObject>, timestamp: NSDate)
所以我假设问题是我试图通过 NSDictionary
而不是 Dictionary< String,NSObject>
。如何在这两个不完全等价类型之间进行转换?我应该对所有必须与其他Objective-C组件交互的代码使用 NSDictionary
吗?
so I assume the problem is that I am trying to pass an NSDictionary
instead of a Dictionary<String, NSObject>
. How can I convert between these two not-quite-equivalent types? Should I just be using NSDictionary
for all of the code that has to interact with other Objective-C components?
推荐答案
将字典解码为 Dictionary< String,NSObject>
,而不是 NSDictionary
。
Decode your dictionary as Dictionary<String, NSObject>
instead of NSDictionary
.
let payload = aDecoder.decodeObjectOfClass(NSDictionary.self, forKey: "payload") as! Dictionary<String, NSObject>
由于您使用Cocoa Touch进行序列化和反序列化,所以序列化为 NSDictionary
,但是你可以将它转换为Swift 字典<,>
,根据WWDC 2014 中介Swift
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.
您还可以解码为 NSDictionary
,然后显式强制转换对象如下:
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.
这篇关于如何将NSDictionary转换为Swift字典< String,NSObject> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!