Let's say I have two arrays of the same length:
names = ["Adam", "Bob", "Colin"]
ages = [14, 11, 16]
How could I produce the following dictionary?
people = ["Adam": 14, "Bob": 11, "Colin": 16]
If you're using Swift 4, you can use uniqueKeysWithValues and zip:
let names = ["Adam", "Bob", "Colin"]
let ages = [14, 11, 16]
let people = Dictionary(uniqueKeysWithValues: zip(names, ages))
print(people) // ["Adam": 14, "Colin": 16, "Bob": 11]
Otherwise, you could just use zip with a for loop:
let names = ["Adam", "Bob", "Colin"]
let ages = [14, 11, 16]
var people = [String: Int]()
for (name, age) in zip(names, ages) {
people[name] = age
}
print(people) // ["Adam": 14, "Bob": 11, "Colin": 16]
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