Tobi.M
Tobi.M

Reputation: 17

Xcode: Error: Index out of Range with array

I have a function to delete Elements of an array at a certain position. After executing I get the Error: Index out of range. I don't know why. My Code is marked with the Error at "if self.liked1[j].id == id.id{". Can someone help me. Thanks in advance.

  func remove(id: datatype2){
        for j in 0..<self.liked1.count{
            
            if self.liked1[j].id == id.id{
                
                self.liked1.remove(at: j)
                
                let db = Firestore.firestore()
                
                db.collection((Auth.auth().currentUser?.email)!).document(self.liked1[j].id).delete()

            }
        }

    }

Upvotes: 0

Views: 90

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236275

When iterating your collection indices and removing elements at the same time you should always do it backwards All you need is to iterate your collection indices reversed:

func remove(id: datatype2){
    for index in self.liked1.indices.reversed() { 
        if self.liked1[index].id == id.id {
            self.liked1.remove(at: index)
            Firestore.firestore().collection(Auth.auth().currentUser!.email).document(self.liked1[index].id).delete()
        }
    }
}

Upvotes: 1

Claudio
Claudio

Reputation: 5193

Every time you call remove(at: ) the array is reindexed and gets smaller, but the foor loop will still loop from 0 to the initial array size, and that's why you get the index out of bounds error.

Upvotes: 0

Related Questions