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