yoninja yoninja - 3 months ago 9
Swift Question

In Swift, what is the best way to assign two arrays to key/value of a dictionary?

Suppose I have two arrays:

let myKeys = ["one", "two", "three"]
let myValues = ["1", "2", "3"]


and empty dictionary:

var myDictionary = Dictionary<String, String>()


What is the best way to assign
myKeys
and
myValues
as keys and values, respectively, of
myDictionary
?

Answer

With my knowledge, this is the way to assign values/keys for your dictionary:

let count = myKeys.count
let count2 = myValues.count
if (count == count2) {
    for index in 0..count {
        myDictionary.updateValue(myValues[index], forKey:myKeys[index])
    }
}

Edit: Swift 2

let count = myKeys.count
let count2 = myValues.count
if (count == count2) {
    for index in 0 ..< count {
        myDictionary.updateValue(myValues[index], forKey:myKeys[index])
    }
}