Reputation: 3057
In Swift I want to make an array of dictionaries (with multiple key value pairs) and then iterate over each element
Below is the expected output of a possible dictionary. Not sure how to declare and intitialize it (somewhat similar to array of hashes in Ruby)
dictionary = [{id: 1, name: "Apple", category: "Fruit"}, {id: 2, name: "Bee", category: "Insect"}]
I know how to make an array of dictionary with one key value pair. For example:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
Upvotes: 4
Views: 10364
Reputation: 15804
to declare an array of dictionary, use this:
var arrayOfDictionary: [[String : AnyObject]] = [["id" :1, "name": "Apple", "category" : "Fruit"],["id" :2, "name": "Microsoft", "category" : "Juice"]]
I see that in your dictionary, you mix number with string, so it's better use AnyObject instead of String for data type in dictionary. If after this code, you do not have to modify the content of this array, declare it as 'let', otherwise, use 'var'
Update: to initialize within a loop:
//create empty array
var emptyArrayOfDictionary = [[String : AnyObject]]()
for x in 2...3 { //... mean the loop includes last value => x = 2,3
//add new dictionary for each loop
emptyArrayOfDictionary.append(["number" : x , "square" : x*x ])
}
//your new array must contain: [["number": 2, "square": 4], ["number": 3, "square": 9]]
Upvotes: 5
Reputation: 10961
let airports: [[String: String]] = [["YYZ": "Toronto Pearson", "DUB": "Dublin"]]
for airport in airports {
print(airport["YYZ"])
}
Upvotes: 1
Reputation: 20205
let dic_1: [String: Int] = ["one": 1, "two": 2]
let dic_2: [String: Int] = ["a": 1, "b": 2]
let list_1 = [dic_1, dic_2]
// or in one step:
let list_2: [[String: Int]] = [["one": 1, "two": 2], ["a": 1, "b": 2]]
for d in list_1 { // or list_2
print(d)
}
which results in
["one": 1, "two": 2]
["b": 2, "a": 1]
Upvotes: 1