Search code examples
swiftswift-arrayswift-dictionary

Swift: dictionaries inside array


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?


Solution

  • 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.