所以,我有一个与此类似的 for 循环:
for var i = 0; i < results.count ; i += 1 {
if (results[i] < 5) {
results.removeAtIndex(i)
i -= 1
}
}
这曾经有效。但是当我将其更改为首选 Swift 3.0 语法时:
for var i in 0..<results.count {
if (results[i] < 5) {
results.removeAtIndex(i)
i -= 1
}
}
我收到数组 IOOBE 异常,因为它不会重新检查计数并继续直到原始计数results.count
.
我该如何解决?现在可以了,但我不想将来遇到麻烦。
虽然解决方案利用filter
是一个很好的解决方案,而且更多Swift-ly,还有另一种方法,如果利用for-in
尽管如此,仍然希望:
func removeBelow(value: Int) {
var results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in (0 ..< results.count).reversed() {
if (results[i] < value) {
results.remove(at: i)
}
}
print(results)
}
removeBelow(value: 5)
Result:
[5, 6, 7, 8, 9, 10]
问题在于removeAtIndex
循环内的一点是它不会导致数组重新索引自身in-place从而导致数组越界异常count
没有被更新。
通过向后遍历,就可以避免越界异常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)