ios 如何在 Swift 3 中为我在 for 循环期间修改的数组编写 for 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37596063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write a for-loop in Swift 3 for an array that I modify during the for loop?
提问by QuantumHoneybees
So, I have a for-loop that looks similar to this:
所以,我有一个与此类似的 for 循环:
for var i = 0; i < results.count ; i += 1 {
if (results[i] < 5) {
results.removeAtIndex(i)
i -= 1
}
}
This used to work. But when I changed it to the preferred Swift 3.0 syntax:
这曾经奏效。但是当我将其更改为首选的 Swift 3.0 语法时:
for var i in 0..<results.count {
if (results[i] < 5) {
results.removeAtIndex(i)
i -= 1
}
}
I get an array IOOBE exception because it doesn't re-check the count and continues on until the original results.count
.
我收到一个数组 IOOBE 异常,因为它不会重新检查计数并继续直到原始results.count
.
How do I fix this? It works now, but I don't want to get into trouble in the future.
我该如何解决?它现在有效,但我不想在将来惹上麻烦。
回答by Unheilig
While the solution making use of filter
is a fine solution and it's more Swift-ly, there is another way, if making use of for-in
is, nonetheless, still desired:
虽然使用 of 的解决方案filter
是一个很好的解决方案,而且它更Swift-ly,但还有另一种方法,如果使用 offor-in
仍然需要:
var results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for var i in (0..<results.count).reverse()
{
if (results[i] < 5)
{
results.removeAtIndex(i)
//i -= 1
}
}
print(results)
Result:
结果:
[5, 6, 7, 8, 9, 10]
We could omit this line i -= 1
altogether, in addition.
此外,我们可以i -= 1
完全省略这一行。
The problem with removeAtIndex
within the loop is that it will not cause the array to re-index itself in-placeand thus causing an array out of bounds exception due to count
not being updated.
removeAtIndex
循环内的问题在于它不会导致数组就地重新索引自身,从而导致由于count
未更新而导致数组越界异常。
By traversing backwards, the out of bounds exception can thus be avoided.
通过向后遍历,可以避免越界异常。
回答by Brandon Shega
Could you use a filter
instead?
你可以用 afilter
代替吗?
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let greaterThan5 = numbers.filter{for (index, element) in results.enumerate() {
if (element < 5) {
results.removeAtIndex(index)
}
}
>= 5}
print(greaterThan5)
回答by Luka Jacobowitz
If you want to continue using a for
-loop, you can enumerate over both index and element using enumerate
:
如果要继续使用for
-loop,可以使用以下方法枚举索引和元素enumerate
:
for var i in (0..<results.count) where results.indices.contains(i) {
//if the index doesn't exist, the loop will be stopped.
if (results[i] < 5) {
results.removeAtIndex(i)
}
}
Although depending on what you're doing in your loop, the filter
method might be a better idea.
尽管取决于您在循环中做什么,该filter
方法可能是一个更好的主意。
回答by Miguel Herrero
If your loop goes forward...
如果你的循环继续......
##代码##