How to remove item in Array? [duplicate]

2019-02-24 20:29发布

This question already has an answer here:

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)

标签: ios swift swift3
1条回答
Animai°情兽
2楼-- · 2019-02-24 21:07

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)}
查看更多
登录 后发表回答