迭代和变异字典数组Swift 3 [英] Iterate and mutate an Array of Dictionaries Swift 3

查看:87
本文介绍了迭代和变异字典数组Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在当前的Swift文档中引用了这一点:

I am referencing this in the current Swift documentation:

您还可以遍历字典以访问其键值对.迭代字典时,字典中的每个项目都将作为(键,值)元组返回,并且您可以将(键,值)元组的成员分解为明确命名的常量,以便在for-in循环的主体中使用.在这里,字典的键被分解为一个名为animalName的常数,而字典的值被分解为一个称为legCount的常数.

You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop. Here, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆