gpt4 book ai didi

Swift:使用 array1 中的键和 array2 中的值构建一个字典

转载 作者:可可西里 更新时间:2023-11-01 00:17:04 24 4
gpt4 key购买 nike

这里有 2 个数组:countriesVotedKeys 和 dictionnaryCountriesVotes。

我需要构建一个字典,它的键是 countriesVotedKeys 中的所有项目,它的值是 dictionnaryCountriesVotes 中的所有项目。两个数组都包含相同数量的元素。我尝试了很多东西,但没有一个能达到预期的结果。

     for value in self.countriesVotedValues! {
for key in self.countriesVotedKeys! {
self.dictionnaryCountriesVotes![key] = value
}
}

我可以清楚地看到为什么这段代码会产生错误的结果:第二个数组在第一个数组的每次迭代中都被完整地迭代。我还尝试了一个经典的 for var i= 0, var j= 0;...... 但似乎这种语法在 swift 中是不允许的。简而言之,我被困住了。再次。

最佳答案

swift 4

let keys = ["key1", "key2", "key3"]
let values = [100, 200, 300]

let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))

print(dict) // "[key1: 100, key3: 300, key2: 200]"

swift 3

var dict: [String: Int] = [:]

for i in 0..<keys.count {
dict[keys[i]] = values[i]
}

关于Swift:使用 array1 中的键和 array2 中的值构建一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com