Convert NSDictionary to Swift Dictionary

2019-01-23 00:40发布

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

4条回答
2楼-- · 2019-01-23 01:14

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楼-- · 2019-01-23 01:24

use:

let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;
查看更多
We Are One
4楼-- · 2019-01-23 01:24

Just declare that it is Swift dictionary

var values: [String: AnyObject] = [
   "key1": 100,
   "key2": "meow",
]

values["key3"] = 20
查看更多
劫难
5楼-- · 2019-01-23 01:34

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
查看更多
登录 后发表回答