如何删除数组中的项目? [英] How to remove item in Array?

查看:95
本文介绍了如何删除数组中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 进行编码,并对一个问题感到困惑. 当我尝试在数组枚举期间从数组中删除一项时,遇到索引超出范围错误.

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.

这是我的错误代码:

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

这是否意味着在每个for循环期间都不会调用array.enumerate()?

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

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}

,或者对于多个值,请使用Set:

or, for multiple values, use Set:

let unwantedValues: Set<Int> = [2, 4, 5]
array = array.filter{!unwantedValues.contains($0)}

同一行:

array = array.filter{!Set([2, 4, 5]).contains($0)}

这篇关于如何删除数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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