I'm new in swift and I need help with deleting colleciton view cell. In this code, if indexPath is 0, i have error with deleting that cell.
@IBAction func deleteItem(_ sender: Any) {
if let selectedCells = tablesCollectionView.indexPathsForSelectedItems{
let items = selectedCells.map {$0.item}.sorted().reversed()
for item in items {
tables.remove(at: item)
let tableNo: TableModel
tableNo = tables[item-1] //Thread 1: Fatal error: Index out of range
refTables = Database.database().reference().child("userInfo").child(uid!).child("tables")
refTables.child(tableNo.id!).removeValue { error,arg in
if error != nil {
print("error \(error)")
}
}
}
tablesCollectionView.deleteItems(at: selectedCells)
deleteButton.isEnabled = false
}
}
I have this message "Thread 1: Fatal error: Index out of range" when I try to delete the cell with 0 indexPath.
CodePudding user response:
This line
tables.remove(at: item)
Is dangerous inside a for
loop , as while you delete from array it's size changes which make old indices goes wrong
You need
var toDeleteIds = [String]()
for item in items {
let tableNo = tables[item]
toDeleteIds.append(tableNo.id!)
refTables = Database.database().reference().child("userInfo").child(uid!).child("tables")
refTables.child(tableNo.id!).removeValue { error,arg in
if error != nil {
print("error \(error)")
}
}
}
tables.removeAll { toDeleteIds.contains($0.id) }