convert array to dictionary

How do I convert an array into a dictionary?

Accepted Answer

You will have to create the keys ; how do you want to define them ?


If you have an array :

let myArray : [String] = ["First", "Second", "Third"]


and you want to put in a dictionary, with a Int Key, to get [1: "First", 2: "Second", 3: "Third"]

var myDict : [Int : String]

You can populate like this

for i in 1...myArray.count {
     myDict[i] = myArray[i]
}


You could also have the keys in another array

let myKeys : [Int] = [1, 2, 3]     // Take care, keys must be unique
for i in 1...myArray.count where i < myKeys.count {  // double check to avoid to exceed any range
     myDict[myKeys[i]] = myArray[i]
}


You could also use the zip function

zip(myKeys, myArray).forEach { myDict[$0] = $1 }


Hope that answers your question.

convert array to dictionary
 
 
Q