我在当前的Swift文档中引用了这个:
您还可以遍历字典以访问其键值对。当迭代字典时,字典中的每个项都作为(键,值)元组返回,并且您可以将(键,值)元组的成员分解为明确命名的常量,以便在for-in循环的主体内使用。在这里,字典的键被分解为一个名为animalName的常量,字典的值被分解为一个名为legCount的常量。
让numberOfLegs = [“蜘蛛”:8,“蚂蚁”:6,“猫”:4]
for(animalName, legCount)in numberOfLegs {
print("\(animalName)s have \(legCount) legs") }
//蚂蚁有6条腿//蜘蛛有8条腿//猫有4条腿
但是,当我动态创建一个字典数组时,该代码不起作用:
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
}
上面的例程成功地创建了字典数组,但是当我尝试按照文档显示迭代它时:
for (wordText, wordCounter) in arrayOfMutatingDictionaries
我收到错误:表达式类型[[String:Int]]含糊不清,没有更多上下文
我根本不明白。
这里的目标是拥有一个可变数组的可变字典。在程序的过程中,我想添加新的键值对,但也可以在必要时增加值。我没有和这个集合类型结婚,但我认为它会起作用。
有什么想法吗?
答案 0 :(得分:3)
您正在尝试迭代数组,将其视为字典。 你必须遍历数组然后通过你的键/值对
for dictionary in arrayOfMutatingDictionaries{
for (key,value) in dictionary{
//Do your stuff
}
}
添加键/值对非常简单。
for i in 0..< arrayOfMutatingDictionaries.count{
arrayOfMutatingDictionaries[i][yourkey] = yourvalue
}
您也可以像这样增加现有值
for i in 0..<arrayOfMutatingDictionaries.count{
for (key,value) in arrayOfMutatingDictionaries[i]{
arrayOfMutatingDictionaries[i][key] = value+1
}
}
答案 1 :(得分:2)
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
}
for dictionary in arrayOfMutatingDictionaries { // You missed this out!
for (word, num) in dictionary {
print(word, num)
}
}
答案 2 :(得分:0)
试试这个。而且你会得到你期望的结果。
let wordArray = ["Man","Child","Woman","Dog","Rat","Goose"]
var arrayOfMutatingDictionaries = [String]()
//Here you are doing mistake in above line. You are creating an array of dictionary ([[String:Int]]) in your code. And you are iterating an array of string (wordArray)
var count = 0
while count < 6
{
arrayOfMutatingDictionaries.append(wordArray[count])
count += 1
}
for (wordText) in arrayOfMutatingDictionaries
{
print(wordText)
}