Convert NSDictionary to Swift Dictionary

天大地大妈咪最大 提交于 2019-12-29 03:50:28

问题


Now I know that when swift compiles it just makes a NSDictionary, but the NSDictionary and Swift dictionaries have different syntax. Is there a way (through a loop or something) to convert a NSDictionary to a swift dictionary of the same type for <key, value>?

OR

Is there a way to convert this to a Swift dictionary instead of NSDictionary?

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

回答1:


use:

let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;



回答2:


I found answer from 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
    }
}



回答3:


NSDictionary and Dictionary are pretty much interchangeable. So there's no need to, but yes you can:

let jsonDict = (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary) as Dictionary


来源:https://stackoverflow.com/questions/24569447/convert-nsdictionary-to-swift-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!