For swipe to delete, return a destructive UIContextualAction from trailingSwipeActionsConfigurationForRowAt: remove the item from your array first, then call deleteRows. Keep the deleted item for an Undo button. For deleting many rows, turn on allowsMultipleSelectionDuringEditing and delete the selected ones together. If the screen shows a total, compute it from the array so it's always right after a delete.
SWIFT TIPS · UIKIT
First posted on July 2, 2018 for Swift 4, as "[TABEL VIEW] Add, Delete Row and value in UItabelView". Rewritten on November 17, 2026. The Swift code below was type-checked on a Mac with Xcode 26.2 against the iOS 26.2 SDK, in Swift 5 and Swift 6 language modes, with iOS 15 as the deployment target. It wasn't run on a device.
This post was the sequel to one about adding rows with a running total in rupiah. In 2018 the next step was deleting: swipe a row away, and subtract its value from the total. The post used tableView(_:commit:forRowAt:), subtracted Int(List[indexPath.row])! from the sum, removed the row and updated the label.
The add post has its own rewrite, which replaces the running sum with a total computed from the rows. This one covers the deleting side in more depth: one row, many rows, and taking a delete back.
Delete, undo and multi-select
import UIKit
struct Expense: Hashable {
let id = UUID()
var title: String
var amount: Decimal
}
final class EditableExpensesViewController: UITableViewController {
private var expenses = [
Expense(title: "Coffee", amount: 25_000),
Expense(title: "Lunch", amount: 45_000),
Expense(title: "Taxi", amount: 60_000),
]
private var lastDeleted: (expense: Expense, index: Int)?
private var totalText: String {
expenses.reduce(Decimal(0)) { $0 + $1.amount }.formatted(.currency(code: "IDR"))
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.allowsMultipleSelectionDuringEditing = true
navigationItem.rightBarButtonItem = editButtonItem
updateTitle()
}
private func updateTitle() { title = "Total \(totalText)" }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { expenses.count }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var content = UIListContentConfiguration.valueCell()
content.text = expenses[indexPath.row].title
content.secondaryText = expenses[indexPath.row].amount.formatted(.currency(code: "IDR"))
cell.contentConfiguration = content
return cell
}
// One row: swipe left, delete, offer undo
override func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in
self?.deleteRow(at: indexPath)
done(true)
}
return UISwipeActionsConfiguration(actions: [delete])
}
private func deleteRow(at indexPath: IndexPath) {
lastDeleted = (expenses[indexPath.row], indexPath.row)
expenses.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
updateTitle()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Undo", primaryAction: UIAction { [weak self] _ in
self?.undoDelete()
})
}
private func undoDelete() {
guard let (expense, index) = lastDeleted else { return }
let row = min(index, expenses.count)
expenses.insert(expense, at: row)
tableView.insertRows(at: [IndexPath(row: row, section: 0)], with: .automatic)
lastDeleted = nil
navigationItem.leftBarButtonItem = nil
updateTitle()
}
// Several rows: Edit, select, delete them in one go
func deleteSelectedRows() {
guard let selected = tableView.indexPathsForSelectedRows, !selected.isEmpty else { return }
let rows = Set(selected.map(\.row))
expenses = expenses.enumerated().filter { !rows.contains($0.offset) }.map(\.element)
tableView.deleteRows(at: selected, with: .automatic)
updateTitle()
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
navigationItem.leftBarButtonItem = editing
? UIBarButtonItem(title: "Delete", primaryAction: UIAction { [weak self] _ in self?.deleteSelectedRows() })
: nil
}
}
One row at a time
tableView(_:commit:forRowAt:) from 2018 still works and is the shortest way to get swipe to delete. The swipe action API, available since iOS 11, gives you more control: a title, a style, and room for more than one action, such as Delete next to Archive. The done(true) call tells the table the action finished.
Order matters in deleteRow(at:). The data changes first, then deleteRows runs. The table expects its data source to report the new row count, the old one minus the deleted rows, as soon as deleteRows runs. If the array still has the item at that moment, the counts don't match and UIKit stops the app with an exception. I didn't trigger that crash for this rewrite, but it's a common mistake with this API.
Taking it back
Deleting by swipe is quick, which also makes it easy to do by accident. The code keeps the last deleted item and its position, and shows an Undo button in the navigation bar. Undo puts the item back at the same index, clamped to the current count in case other rows changed, and inserts the row with an animation.
For larger apps, UndoManager gives you shake to undo and an undo stack. The single-step version above is enough for many lists.
Many rows at once
editButtonItem gives the familiar Edit and Done button. With allowsMultipleSelectionDuringEditing on, Edit mode shows selection circles. deleteSelectedRows() reads the selected index paths, removes those items from the array in one pass, and deletes all the rows in one call. Building a new array from the items that aren't selected avoids the classic bug of removing by index in a loop, where every removal shifts the indexes after it.
The total stays right
The title shows the total, computed with reduce from expenses after every change. Delete, undo and multi-delete all call updateTitle(), and none of them does arithmetic of its own. That's the difference from 2018, where each path had to subtract or add the right amount from a separate sum.
A quick check for your project
- Find every
deleteRowscall and check that the array is changed before it. - Look for loops that call
remove(at:)with several indexes. Remove from a set of indexes or build a filtered array instead. - Delete a row, tap Undo, then delete two rows in Edit mode, and check the total each time.
What the 2018 version said
The original added two lines to the delete method, sum -= Int(List[indexPath.row])! and labelRp.text = "Rp \(sum)", before removing the row between beginUpdates() and endUpdates(), and showed screenshots of the list before and after. It reminded readers to use += when adding and -= when deleting.
Keep reading on JR Devhub
Comments