skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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()
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search