现在我知道,当swift编译它只是创建一个NSDictionary,但NSDictionary和Swift词典有不同的语法。是否有办法(通过循环或其他方式)将NSDictionary转换为<key, value>
的相同类型的快速字典?
OR
有没有办法将其转换为Swift词典而不是NSDictionary?
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
答案 0 :(得分:26)
使用:
let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;
答案 1 :(得分:4)
我从http://www.swift-studies.com/blog/2014/6/6/loading-a-swift-dictionary-from-a-plist-file
找到答案var swiftDict : Dictionary<String,AnyObject!> = Dictionary<String,AnyObject!>()
for key : AnyObject in ocDictionary.allKeys {
let stringKey = key as String
if let keyValue = ocDictionary.valueForKey(stringKey){
swiftDict[stringKey] = keyValue
}
}
答案 2 :(得分:3)
NSDictionary
和Dictionary
几乎可以互换。所以没有必要,但是你可以:
let jsonDict = (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary) as Dictionary