Reputation: 613
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]()]
Upvotes: 0
Views: 44
Reputation: 274470
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]()
Upvotes: 1