Swift: dictionaries inside array

UpCat picture UpCat · Nov 4, 2014 · Viewed 8.4k times · Source

Data:

[
    { firstName: "Foo", lastName: "Bar" },
    { firstName: "John", lastName: "Doe" }
]

How can I have this kind of structure using swift array and dictionary? This data shows dictionaries inside an array, right? So I suggest:

var persons:Array = [Dictionary<String, String>()]

but this gives me the error:

Cannot convert the expressions type () to type Array<T>

Any ideas?

Answer

Antonio picture Antonio · Nov 4, 2014

The correct way is:

var persons = [Dictionary<String, String>]()

which is equivalent to:

var persons = [[String : String]]()

What your code does instead is to create an array filled in with an instance of Dictionary<String, String>, whereas I presume you want an empty instance of the array containing elements of Dictionary<String, String> type.