Keep the rows in an array of small structs with a Decimal amount, and compute the total from that array, for example with expenses.reduce(0) { $0 + $1.amount }, every time it changes. Don't keep a separate running sum variable that you add to and subtract from. Read the amount by keeping only its digits, so "15.000" and "Rp 15.000" work, and format the total with the currency style.
SWIFT TIPS · UIKIT · FOUNDATION
First posted on June 7, 2018 for Swift 4, as "How to Make Adding data labels to table cell and the sum data cell in Swift 4". Rewritten on November 17, 2026. The total logic was run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The view controller was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 as the deployment target, but not run on a device.
In 2018 I had a screen where the user typed an amount, tapped Add, and saw the amount appear as a new row, with a label showing the total in rupiah. The post kept the rows in a string array, kept a sum integer next to it, and added Int(textIsi.text!)! to the sum on every Add. A follow-up post subtracted from the sum when a row was deleted.
That works until the input isn't a plain number, or until the rows and the sum disagree. Here's a version where they can't.
The total, computed from the rows
First the logic on its own, run on a Mac:
import Foundation
struct Expense: Identifiable {
let id = UUID()
var title: String
var amount: Decimal
}
/// Reads what the user typed as rupiah. Accepts "15000", "15.000" and "Rp 15.000".
func rupiah(from text: String) -> Decimal? {
let digits = text.filter(\.isASCII).filter(\.isNumber)
return digits.isEmpty ? nil : Decimal(string: digits)
}
func show(_ d: Decimal) -> String {
d.formatted(.currency(code: "IDR").locale(Locale(identifier: "id_ID")))
}
var expenses: [Expense] = []
var total: Decimal { expenses.reduce(0) { $0 + $1.amount } }
for typed in ["15000", "Rp 2.500", "abc", "", "7.500"] {
if let amount = rupiah(from: typed) {
expenses.append(Expense(title: "Item \(expenses.count + 1)", amount: amount))
print("added \(typed.debugDescription) -> total \(show(total))")
} else {
print("skipped \(typed.debugDescription): not an amount")
}
}
// Delete the second row, then edit the first: the total follows the data
expenses.remove(at: 1)
print("after deleting row 2 -> total \(show(total))")
expenses[0].amount = 20_000
print("after editing row 1 -> total \(show(total))")
added "15000" -> total Rp15.000
added "Rp 2.500" -> total Rp17.500
skipped "abc": not an amount
skipped "": not an amount
added "7.500" -> total Rp25.000
after deleting row 2 -> total Rp22.500
after editing row 1 -> total Rp27.500
Each row is an Expense with a title and a Decimal amount. total is a computed property, so it's always the sum of whatever is in the array right now. Deleting the second row and editing the first both updated the total correctly, with no extra code. Text that isn't an amount, "abc" or an empty field, is skipped instead of crashing.
What the 2018 approach did with "15.000"
In Indonesia people write fifteen thousand as 15.000. I ran the 2018 line, sum += Int(typed)!, with "15000" and then "15.000":
sum += Int("15000")! -> 15000
sum += Int("15.000")! -> Fatal error: Unexpectedly found nil while unwrapping an Optional value
Int("15.000") returns nil, and the ! stops the app. The rupiah(from:) function above keeps only the digits, so 15000, 15.000 and Rp 15.000 all become the same amount.
The separate sum also has a quieter problem: it's a second copy of the truth. Every path that changes the rows, adding, deleting, editing, undoing, has to remember to update it. Miss one and the label is wrong. Computing the total from the rows removes that whole class of bug.
The screen
import UIKit
struct Expense: Hashable {
let id = UUID()
var title: String
var amount: Decimal
}
final class ExpensesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet private weak var amountField: UITextField!
@IBOutlet private weak var totalLabel: UILabel!
@IBOutlet private weak var tableView: UITableView!
private var expenses: [Expense] = [] {
didSet { totalLabel.text = Self.rupiah(expenses.reduce(0) { $0 + $1.amount }) }
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
amountField.keyboardType = .numberPad
totalLabel.text = Self.rupiah(0)
}
@IBAction func addTapped(_ sender: UIButton) {
let digits = (amountField.text ?? "").filter(\.isASCII).filter(\.isNumber)
guard let amount = Decimal(string: digits), amount > 0 else { return }
expenses.append(Expense(title: "Item \(expenses.count + 1)", amount: amount))
tableView.insertRows(at: [IndexPath(row: expenses.count - 1, section: 0)], with: .automatic)
amountField.text = nil
}
static func rupiah(_ value: Decimal) -> String {
value.formatted(.currency(code: "IDR"))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { expenses.count }
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 = Self.rupiah(expenses[indexPath.row].amount)
cell.contentConfiguration = content
return cell
}
// Swipe to delete: remove from the data, and the total updates itself
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
expenses.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
The didSet on expenses updates the total label whenever the array changes, so addTapped and the delete method only touch the data and the table. Each cell uses a value-cell configuration that shows the title on the left and the amount on the right. The amount field uses the number pad, so most users can't type letters in the first place.
Formatting with .currency(code: "IDR") follows the user's region, so an Indonesian device shows Rp15.000, as in the test output above, and other regions see their own separators.
A quick check for your project
- Search for a total or sum variable that is changed with
+=or-=next to an array. Replace it with a value computed from the array. - Type an amount with a thousands separator, like 15.000, into every money field.
- Delete a row, then add one, then delete another, and check the total against the rows by hand.
What the 2018 version said
The full controller registered a cell from a XIB, inserted a row on each Add, and showed the sum in labelRp. It started the list with one empty string, var List: [String] = [""], which puts an empty first row in the table. Type-checked with Xcode 26.2, it fails mainly on Swift 4 names that have since changed, such as UITableViewAutomaticDimension (now UITableView.automaticDimension) and UIEdgeInsetsMake.
Keep reading on JR Devhub
Comments