When you filter an array, the indices
will not match what you started with. Why? Because you are creating a brand new array with its own indices.
import Foundation
//start with an array of Ints
let a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//print the values
print(a1) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//and their indices
print(a1.indices.map { $0 }) //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//filter it to only contain the even numbers
let a2 = a1.filter { $0.isMultiple(of: 2) }
//print the values
print(a2) //[2, 4, 6, 8, 10]
//and their indices
print(a2.indices.map { $0 }) //[0, 1, 2, 3, 4]
You can see that in a1
, the index 1
has the value 2
but in a2
the index 1
has the value 4
. So if you use the indices from a2
to delete an element from a1
, you’ll delete the wrong item.
So when you call deleteRow
using an IndexSet
from your filtered array, you can’t use that value to index into your original array; you’ll get different items back.
When you delete an item from your filtered array, you’ll need to figure out what the index of the item is in the original array and then delete it using that index.