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"]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With