How to swipe to delete UITableViewCells in Swift 5

January 21, 2018 ยท 1 minute read

When you want to handle deleting a row, you have to add the do three things and in this order:

  1. Check that it’s a delete that’s happening and not an insert (this is down to how you use the UI);
  2. Delete the item from the data source you used to build the table; and
  3. Call the deleteRows(at:) method on your table view.

It is crucial that you do those things in exactly this order. iOS checks the number of rows before and after a delete operation, and expects them to add up correctly following the change.

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) 
    if editingStyle == .delete {
        objects.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    else if editingStyle == .insert 
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.