How to solve Fatal Error: Index out of range error in swift?

In this piece of code, when the iteration position reach 13 out of an array with 20 elements, it crashes with the index out of range error.

let counterHeaders = headers.count
for value in 0..<(counterHeaders){
    if headers[value] == "" {
        headers.remove(at: value)
    }
}

Note: counterHeaders variable was created to check how many values was in headers array


Solution 1:

You just need to iterate your indices in reverse order when removing items in your collection.

for value in headers.indices.reversed() {
    if headers[value] == "" {
        headers.remove(at: value)
    }
}

Note also there is a mutating method that accepts a predicate called removeAll(where:):

headers.removeAll(where: \.isEmpty)