简体   繁体   English

快速过滤数组元素

[英]Swift Filtering array elements

I am creating a function that will filter an array, 我正在创建一个将过滤数组的函数,
eg x = [10,20,30,40,50] 例如x = [10,20,30,40,50]
filter(x,10,20) 过滤器(X,10,20)
output should be 30,40,50. 输出应为30、40、50。
I am getting an index out of bounds error . 我得到索引超出范围错误。 Here's my code: 这是我的代码:

func filterArray( _ x:  [Int], _ nums: Int...) -> [Int]{
var arrayX = x
    for i in 0...arrayX.count-1{
        for j in 0...nums.count-1 {
            if arrayX[i] == nums[j]{//Changed arrayX to x because x was never changed
             if let index = arrayX.index(of: nums[j]) {
                    arrayX.remove(at: index) //error is here
                }
                else{

                }
            }
        }
    }
    return arrayX
}

var mArray = [10,20,30,40,50]
filterArray(mArray,10)

The way you are doing it is not correct, you are altering an array while looping through it. 您做的方式不正确,您正在遍历数组时更改了数组。 When you remove an object from the array, the array count changes but the loop still run using the previously calculated array.count value. 当您从数组中删除对象时,数组计数会更改,但是循环仍将使用先前计算的array.count值运行。

There is a much simpler way of doing this, you just need to combine filter and contains functions together for achieving this: 有一种更简单的方法,您只需要组合filtercontains函数即可实现此目的:

func filterArray( _ x:  [Int], _ nums: Int...) -> [Int]
{
    let filteredArray = x.filter({ !nums.contains($0)})
    return filteredArray
}

从数组中删除一个元素后,其大小会发生变化,但是循环仍将继续进行,直到导致该问题的先前计数为止,尝试使其他数组通过该循环并存储结果,而无需找到其索引已经存在,“ i”的值就是元素的索引。

You function can be faster if you use a Set . 如果使用Set则功能可以更快。

func filter(list: [Int], _ remove: Int...) -> [Int] {
    let removeSet = Set(remove)
    return list.filter { removeSet.contains($0) }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM