问题描述
我在当前的Swift文档中引用了这一点:
I am referencing this in the current Swift documentation:
let numberOfLegs = [蜘蛛":8,蚂蚁":6,猫":4]
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
对于(animalName, legCount)in numberOfLegs {
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs") }
//蚂蚁有6条腿//蜘蛛有8条腿//猫有4条腿
// ants have 6 legs // spiders have 8 legs // cats have 4 legs
但是,当我动态创建字典数组时,该代码不起作用:
However, when I create an array of dictionaries dynamically, that code does not function:
let wordArray = ["Man","Child","Woman","Dog","Rat","Goose"]
var arrayOfMutatingDictionaries = [[String:Int]]()
var count = 0
while count < 6
{
arrayOfMutatingDictionaries.append([wordArray[count]:1])
count += 1
}
上面的例程按预期成功创建了字典数组,但是当我尝试遍历字典时,如文档所示:
The above routine successfully creates the array of dictionaries, as it should, but when I try to iterate through it like the documentation shows:
for (wordText, wordCounter) in arrayOfMutatingDictionaries
我收到一个错误:表达式类型[[String:Int]]含糊不清,没有更多上下文
我一点都不明白.
这里的目标是要有可变字典的可变数组.在整个程序过程中,我想添加新的键值对,但也可以在必要时增加值.我并没有嫁给这种收藏类型,但我认为它会起作用.
The goal here is to have a mutable array of mutable dictionaries. Over the course of the program, I want to add new Key-Value pairs, but also be able to increment the values if necessary. I am not married to this collection type, but I thought it would work.
有什么想法吗?
推荐答案
您正尝试遍历数组,将其视为字典.您必须遍历数组,然后遍历键/值对
You are trying to iterate through an array treating it like a dictionary.You'll have to iterate through the array and then through your key/value pairs
for dictionary in arrayOfMutatingDictionaries{
for (key,value) in dictionary{
//Do your stuff
}
}
添加键/值对非常简单.
Adding a key/value pair is pretty straightforward.
for i in 0..< arrayOfMutatingDictionaries.count{
arrayOfMutatingDictionaries[i][yourkey] = yourvalue
}
您还可以像这样增加现有值
You can also increment the existing values like this
for i in 0..<arrayOfMutatingDictionaries.count{
for (key,value) in arrayOfMutatingDictionaries[i]{
arrayOfMutatingDictionaries[i][key] = value+1
}
}
这篇关于迭代和变异字典数组Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!