在Swift中将两个数组转换成字典

时间:2018-07-11 07:11:01

标签: arrays swift dictionary

假设我有两个相同长度的数组:

names = ["Adam", "Bob", "Colin"]
ages = [14, 11, 16]

我如何制作以下词典?

people = ["Adam": 14, "Bob": 11, "Colin": 16]

1 个答案:

答案 0 :(得分:1)

如果您使用 Swift 4 ,则可以使用 uniqueKeysWithValues 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]

否则,您可以将zip与for循环一起使用:

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]