Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Dictionary Multiple Key Value Pairs - Iteration

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"] 
like image 326
Anuj Arora Avatar asked Mar 14 '23 13:03

Anuj Arora


1 Answers

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]]
like image 157
Duyen-Hoa Avatar answered Apr 02 '23 20:04

Duyen-Hoa