I am coding with Swift, and confuse with one problem. I encountered Index out of Range Error when I am trying to remove one item from array during the array's enumeration.
Here is my error codes:
var array :[Int] = [0,1,2,3,4,5]
for (index, number) in array.enumerate() {
if array[index] == 2 {
array.removeAtIndex(index) // Fatal error: Index out of range
}
}
Does that means array.enumerate() not be called during each for loop?
I have to change my codes like that:
for number in array {
if number == 2 || number == 5 {
array.removeAtIndex(array.indexOf(number)!)
}
}
Or
var index = 0
repeat {
if array[index] == 2 || array[index] == 4 {
array.removeAtIndex(index)
}
index += 1
} while(index < array.count)
You are removing item at the same time when you are enumerating same array. Use filter instead:
var array: [Int] = [0,1,2,3,4,5]
array = array.filter{$0 != 2}
or, for multiple values, use Set:
let unwantedValues: Set<Int> = [2, 4, 5]
array = array.filter{!unwantedValues.contains($0)}
Same in one line:
array = array.filter{!Set([2, 4, 5]).contains($0)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With