AJS AJS - 4 months ago 26
iOS Question

fatal error: Index out of range (lldb) when removing from index in array swift

I am trying to make a method that compares two arrays, list and id. My goal is to check to see if any of the ints stored in id is also stored in list, then remove said int from list. I keep getting an error whenever I run the line that removes the index. Here is my code:

func removal(id: [UInt8]){
var list: [UInt8] = [1,2,3,4,5,6,7,8,9]

for k in 0 ..< id.count {
for j in 0 ..< list.count {
if list[j] == id[k]{
list.removeAtIndex(j)
}
}
}
}

removal([2])


The error that I am receiving is...

Prints in console:
fatal error: Index out of range (lldb)


In the text editor:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)

Answer

When you call list.removeAtIndex the j is now off by 1. So when ever you call list.removeAtIndex you do not want to update j by one. For example with id=[2] and list=[1,2,3] when removal removes 2 from list, the variable j will be incremented to 2 and try to access the array at index 2 which is out of bounds.

Here is a not so pretty solution (should work) :

func removal(id: [UInt8]){
    var list: [UInt8] = [1,2,3,4,5,6,7,8,9]
    var index = 0
    for k in 0 ..< id.count {
        while index < list.count {
            if list[index] == id[k]{
                list.removeAtIndex(index)
            } else{
                index++
            }
        }
        index=0
    }
}