Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: build a dictionary with keys from array1, and values from array2

Tags:

swift

Here are 2 arrays: countriesVotedKeys and dictionnaryCountriesVotes.

I need to build a dictionary, whose keys are all the items from countriesVotedKeys, and its values are all the items from dictionnaryCountriesVotes. Both arrays contains same number of elements. I've tried many things, but none lead to desired result.

     for value in self.countriesVotedValues! {
        for key in self.countriesVotedKeys! {
            self.dictionnaryCountriesVotes![key] = value
        }
    }

I can clearly see why this code produce bad result: second array is iterated in its entirity at each iteration of first array. I also tried a classical for var i= 0, var j= 0;...... but it seems this kind of syntax is not allowed in swift. In short, i'm stuck. Again.

like image 614
Robert Brax Avatar asked Feb 11 '23 07:02

Robert Brax


1 Answers

Swift 4

let keys = ["key1", "key2", "key3"]
let values = [100, 200, 300]

let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))

print(dict)   // "[key1: 100, key3: 300, key2: 200]"

Swift 3

var dict: [String: Int] = [:]

for i in 0..<keys.count {
    dict[keys[i]] = values[i]
}
like image 170
Leo Dabus Avatar answered Feb 13 '23 21:02

Leo Dabus