Convert NSDictionary to Swift Dictionary
Asked Answered
G

3

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
Gelding answered 4/7, 2014 at 8:1 Comment(1)
under the hood the Swift Dictionary is literally an Obj-C NSMutableDictionary, you can bridge them toll-free.Spanjian
R
28

use:

let jsonDic = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary<String, AnyObject>;
Ryley answered 29/8, 2014 at 9:29 Comment(2)
For some reason, that didn't work for me. What worked for me was let b = d as [NSObject:AnyObject]Ilocano
For SWIFT 3 you can use JSONSerialization.Lockard
U
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
    }
}
Unchartered answered 2/3, 2015 at 2:7 Comment(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.Headliner
S
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
Shorttempered answered 4/7, 2014 at 8:7 Comment(4)
Are they what? Interchangeable with their counterparts? Yes.Shorttempered
I keep having to type out as NSString everywhere though and ti doesn't like as String. Maybe this is because I'm defining jsonDict : [[String:AnyObject]]?Shuttlecock
I believe it is, when going from AnyObject to anything, you have to cast it.Shorttempered
Beware bridging if NSDictionary to Dictionary is not toll free.Irrepealable

© 2022 - 2024 — McMap. All rights reserved.