Brejuro Brejuro - 11 months ago 39
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 == "banana" {
var orange = Ingredient(name: "orange")
if == "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?


try this:

var array = ["a", "b"]

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