soleil soleil - 2 years ago 107
Swift Question

Array of dictionaries in Swift

Can't seem to find the right syntax. Trying to get an array of dicts from a json file:

let books:Array = jsonDict["books"] as Array
//Cannot convert the expression's type Array<$T4> to type StringLiteralConvertible

let books:Array = jsonDict["books"] as Array<Dictionary>
//Reference to generic type "Dicionary" requires arguments in <...>

The json looks like this:

"id": "1",
"title": "title one",
"books": [
"id": "1",
"title": "book title one"
"id": "2",
"title": "book title two"

Answer Source

When you specify an Array, you have to also be specific and list what is in the Array. You also need

What you're probably looking for is:

let books = jsonDict["books"]

The compiler should be able to infer what's in there. If not, you can cast using:

let books = jsonDict["books"] as Array<Dictionary<String, String>>

Having the type cast and the type specifier for books is unnecessary.

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