43

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
cclloyd
  • 8,171
  • 16
  • 57
  • 104
  • 3
    under the hood the _Swift_ `Dictionary` is literally an _Obj-C_ `NSMutableDictionary`, you can bridge them toll-free. – holex Jul 04 '14 at 08:31

3 Answers3

28

use:

let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;
Arno van Lieshout
  • 1,570
  • 1
  • 13
  • 19
4

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
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Yang
  • 111
  • 6
  • 1
    Maybe in some very specific cases that may pay off, but I don't think that the overhead in memory, cpu and battery use of making a shallow copy of the NSDictionary has any real advantage. Since you can use an NSDictionary as a regular Dictionary the difference is almost non existent. – ncerezo Jun 24 '15 at 22:08
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
Oxcug
  • 6,524
  • 2
  • 31
  • 46