Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSDictionary to Swift Dictionary

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
like image 913
cclloyd Avatar asked Jul 04 '14 08:07

cclloyd


2 Answers

use:

let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;
like image 176
Arno van Lieshout Avatar answered Nov 09 '22 22:11

Arno van Lieshout


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
    }
}
like image 4
Yang Avatar answered Nov 09 '22 22:11

Yang