Brejuro Brejuro - 4 months ago 8
Swift Question

Adding element to an array while iterating over it

I have a for loop that loops over each element in an array. Under a certain condition, I add another element to that array inside the loop. However, the loop doesn't take that new element into account. If there are 6 items originally in the array and while looping through, I add 2 more, it still only loops 6 times. How can I fix this?

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


If one of my ingredients is a banana, add an orange to the list. However, the loop never even considers the newly added element. How can I accomplish something like this and why doesn't it work?

Answer

try this:

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")
    }
}