QuantumHoneybees QuantumHoneybees - 6 months ago 17
Swift Question

How do I write a for-loop in Swift 3 for an array that I modify during the for loop?

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
}
}


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
}
}


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.

Answer

Could you use a filter instead?

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let greaterThan5 = numbers.filter{$0 >= 5}
print(greaterThan5)
Comments