我有一个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
}
}
如果我的成分之一是香蕉,请在列表中添加橙色。但是,循环甚至不会考虑新添加的元素。我怎样才能完成这样的事情,为什么它不起作用?
试试这个:
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")
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句