这里有2个数组:countriesVotedKeys和dictionnaryCountriesVotes.
我需要构建一个字典,其键是countriesVotedKeys的所有项目,其值是dictionnaryCountriesVotes中的所有项目.两个数组都包含相同数量的元素.我尝试了很多东西,但都没有达到理想的效果.
for value in self.countriesVotedValues! {
for key in self.countriesVotedKeys! {
self.dictionnaryCountriesVotes![key] = value
}
}
Run Code Online (Sandbox Code Playgroud)
我可以清楚地看到为什么这段代码会产生错误的结果:第二个数组在第一个数组的每次迭代中都是迭代的.我也尝试了经典的var i = 0,var j = 0; ......但似乎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]"
Run Code Online (Sandbox Code Playgroud)
斯威夫特3
var dict: [String: Int] = [:]
for i in 0..<keys.count {
dict[keys[i]] = values[i]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |