Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert two arrays into a dictionary in Swift [duplicate]

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]
like image 945
HarveyAC Avatar asked Oct 31 '25 15:10

HarveyAC


1 Answers

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]
like image 132
Sash Sinha Avatar answered Nov 02 '25 05:11

Sash Sinha