0

Let me create these 3 dictionaries:

var animal1 = ["name":"lion", "footCount":"4", "move":"run"]
var animal2 = ["name":"Fish", "footCount":"0", "move":"swim"]
var animal3 = ["name":"bird", "footCount":"2", "move":"fly"]

And then let me create this array:

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

and then let me append above dictionaries in to myArray

myArray.append(animal1)
myArray.append(animal2)
myArray.append(animal3)

I see 4 items if I run below code

print(myArray.count)

because the array is created with one empty item: var myArray= [[String : String]()] So I need to use below code all the time:

myArray.removeFirst()

My question is: Is there another alternative array defination to append above dictionaries? Because I must execute above code all the time if I use this array defination:

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

1 Answer 1

1

You can create an empty array of dictionaries like this:

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

Note that the ()s are outside of the outer []s. Your attempt of [String : String]()] is an array literal containing one element of an empty dictionary, whereas you should be calling the initialiser for the array type of [[String : String]] (aka Array<Dictionary<String, String>>).

Since you have all the elements you want in the array already, you could just do:

var myArray = [animal1, animal2, animal3]

as well.


Seeing how all your dictionary keys are the same though, you should really create a custom struct for this:

struct Animal {
    let name: String
    let footCount: Int
    let move: String
}

And your array can be:

var myArray= [Animal]()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.