Timothy Deng Timothy Deng - 1 year ago 131
JSON Question

Nested dictionaries Swift curly braces?

I'm trying to create a nested dictionary in Swift, so I can change it to JSON later. I am setting it up like this:

let item: [String: AnyObject] = [
"item": item,
"price": price,
"date": date,
"time": time,
"location": [
"store": "Store name",
"address": "1234 Untitled Dr.",
"city": "City",
"state": "CA",
"zip": "12345"

When I run this, the output is this:

["price": 15.69, "location": {
address = "12350 Carmel MT Road";
city = "City";
state = CA;
store = "Store name";
zip = 12345;
}, "item": item, "date": , "time": ]

The location value is supposed to be a nested dictionary. Why are there curly braces surrounding the location part? And why are values inconsistent in whether there are quotes? Furthermore, when I try to access:


I am told I:

Cannot subscript a value of type `[[String : AnyObject]]' with an
index of type 'String'

Answer Source

Short answer:
Use [String: Any] instead of [String: AnyObject].

Longer answer::
The thing is Foundation automatically bridges Swift core types to Cocoa. This being said Swift Dictionary is being automatically bridged to NSDictionary because of the AnyObject constraint, a Swift struct can't be casted to an AnyObject and Dictionary is a struct.

The print function calls description property, which for NSDictionarys is with curly braces.

When specifying Any instead of AnyObject Swift will just set the variable type to Dictionary which has the square brackets description.

About the subscript thing, I think you have an array there, so you should use something like items[0]["location"]!["store"].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download