Ralph Macalino Ralph Macalino - 3 months ago 9
iOS Question

Swift Filtering array elements

I am creating a function that will filter an array,
e.g.
x = [10,20,30,40,50]

filter(x,10,20)

output should be 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)

Answer

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.

There is a much simpler way of doing this, you just need to combine filter and contains functions together for achieving this:

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