0

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()

            }
        }

    }

2 Answers 2

1

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()
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Thank You. What can I do to avoid this. I want to remove certain elements. How can I do this without getting the error?
@Tobi.M you can loop the array backwards, like Leo Dabus has shown on his answer. If somehow that is not possible, you can save the indexes and after the loop ends, create another to remove the items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.