假设我有两个相同长度的数组:
names = ["Adam", "Bob", "Colin"]
ages = [14, 11, 16]
我如何制作以下词典?
people = ["Adam": 14, "Bob": 11, "Colin": 16]
答案 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]