Reputation: 121
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)
Upvotes: 2
Views: 1860
Reputation: 59496
You function can be faster if you use a Set
.
func filter(list: [Int], _ remove: Int...) -> [Int] {
let removeSet = Set(remove)
return list.filter { removeSet.contains($0) }
}
Upvotes: 0
Reputation: 21
once you remove one element from array its size change, but your loop is still going till previous count that is causing the issue try taking different array to go through the loop and for storing the result and you don't need to find the index its already there, value of 'i' is the index of the element.
Upvotes: 0
Reputation: 107121
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
}
Upvotes: 3