【问题标题】:Adding element to an array while iterating over it在迭代数组时将元素添加到数组
【发布时间】:2016-11-30 16:25:23
【问题描述】:

我有一个循环遍历数组中每个元素的 for 循环。在特定条件下,我在循环内向该数组添加另一个元素。但是,循环没有考虑到这个新元素。如果数组中最初有 6 个项目并且在循环时,我再添加 2 个,它仍然只循环 6 次。我该如何解决这个问题?

for ingredient in ingredientList {
    if ingredient.name == "banana" {
        var orange = Ingredient(name: "orange")
        ingredientList.append(orange)
    }
    if ingredient.name == "orange" {
        // this never executes
    }
}

如果我的其中一种食材是香蕉,请在列表中添加一个橙子。但是,循环甚至从不考虑新添加的元素。我怎样才能完成这样的事情,为什么它不起作用?

【问题讨论】:

    标签: arrays swift loops


    【解决方案1】:

    试试这个:

    var array = ["a", "b"]
    
    for i in array.startIndex...array.endIndex {
        if array[i] == "b" {
            array.append("c")
            print("add c")
        }
        if array[i] == "c"{
            array.append("d")
            print("add d")
        }
    }
    

    【讨论】:

    【解决方案2】:

    @ghostatron 集合的 indices 属性可以持有对集合本身的强引用,从而导致集合被非唯一引用。如果在迭代集合的索引时改变集合,强引用可能会导致集合的意外副本。为避免意外复制,请改用以 startIndex 开头的 index(after:) 方法生成索引。

    var c = MyFancyCollection([10, 20, 30, 40, 50])
    var i = c.startIndex
    while i != c.endIndex {
        c[i] /= 5
        i = c.index(after: i)
    }
     // c == MyFancyCollection([2, 4, 6, 8, 10])
    

    【讨论】:

      【解决方案3】:

      我认为这里有两个问题:

      1. 一般来说,您不应该在枚举集合时修改它。充其量,它会忽略你。在大多数语言中,它只会崩溃。

      2. 我怀疑您在这里看到的是您的循环正在处理集合的副本,但您的“附加”正在修改原始内容。我的理由是,在 Swift 中,结构通常是副本而不是引用,而且非常奇怪……数组和字典都是结构。

      【讨论】:

        【解决方案4】:

        您需要使用 for 循环而不是 for each 循环,并在添加元素时相应地调整计数器

        Int cntVar = 0
        
        for x as Integer = 0 to ingredientList.count - 1 {
            if ingredientList(x + cntVar).name == "banana" {
                var orange = Ingredient(name: "orange")
                ingredientList.append(orange)
                x = x - 1
                cntVar = cntVar + 1
            }
            if ingredientList(x + cntVar).name == "orange" {
                //add needed function here
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-03-05
          • 2012-08-27
          • 2018-06-29
          • 2018-03-12
          • 2015-05-11
          • 2017-01-15
          • 1970-01-01
          • 1970-01-01
          • 2012-01-23
          相关资源
          最近更新 更多