Search code examples
swiftios8xcode6.1swift-arrayswift-dictionary

Swift: array of dictionaries has count of 1 after initialization but should have 0


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

prints 1. I see that there is an empty dictionary inside the array when it is initialized but is there a way to avoid that and having 0 elements instead of 1? Later I need to be able to do:

persons.append(["firstName": "Foo", "lastName": "Bar"])

Any ideas?


Solution

  • By using this:

    [Dictionary<String, String>()]
    

    you are creating an array with one element Dictionary<String, String>()

    The correct way is to move the parenthesis after the square brackets:

    [Dictionary<String, String>]()
    

    That declares an array of type Dictionary<String, String>, and instantiate it.

    Equivalent way of creating it is:

    Array<Dictionary<String, String>>()