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?
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With