如何在Swift 3中为for循环中修改的数组编写for循环? [英] How do I write a for-loop in Swift 3 for an array that I modify during the for loop?

查看:459
本文介绍了如何在Swift 3中为for循环中修改的数组编写for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个类似于这个的for循环:

So, I have a for-loop that looks similar to this:

for var i = 0; i < results.count ; i += 1 {
   if (results[i] < 5) {
      results.removeAtIndex(i)
      i -= 1
   }
}

这曾经有效。但当我将其更改为首选的Swift 3.0语法时:

This used to work. But when I changed it to the preferred Swift 3.0 syntax:

for var i in 0..<results.count {
   if (results[i] < 5) {
      results.removeAtIndex(i)
      i -= 1
   }
}

我得到一个数组IOOBE异常,因为它不会重新检查计数并继续,直到原来的结果。 count

I get an array IOOBE exception because it doesn't re-check the count and continues on until the original results.count.

我该如何解决这个问题?它现在有效,但我不想在将来遇到麻烦。

How do I fix this? It works now, but I don't want to get into trouble in the future.

推荐答案

虽然解决方案正在使用过滤器是一个很好的解决方案而且它更多是 Swift-ly ,还有另一种方法,如果使用 for-in 仍然需要:

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:

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)

结果:

[5, 6, 7, 8, 9, 10]

我们可以另外省略这行 i - = 1

We could omit this line i -= 1 altogether, in addition.

removeAtIndex 是它不会导致数组自行重新索引就地,从而导致数组超出范围,因为t o count 未更新。

The problem with removeAtIndex within the loop is that it will not cause the array to re-index itself in-place and thus causing an array out of bounds exception due to count not being updated.

通过向后遍历,可以避免出界异常。

By traversing backwards, the out of bounds exception can thus be avoided.

这篇关于如何在Swift 3中为for循环中修改的数组编写for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆