Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 46 ยท Projects

Project: An Expense Tracker

Design an expense tracker for iOS: money as integer cents, currency formatting, grouping by month, filters, Swift Charts and CSV export, with runnable logic.

An expense tracker looks simple: a list of purchases and a total. It is a surprisingly good project, because every part of it hides a classic trap. Money must never be stored in a Double. Dates must be grouped by calendar month, not by "30 days". Filters must combine without producing a tangle of if statements. And exporting to CSV has quoting rules that quietly break files if you ignore them.

In this project you design the app the way a professional would: first the model and the logic, then the SwiftUI screens on top. SwiftUI itself cannot run on this site, so the screens are shown as read-only code. The logic (money, grouping, filtering, totals, CSV) is plain Swift, and you can run all of it in the editors below. That split is also how you should build the real app: logic that does not import SwiftUI is easy to test.

What we are building

Expenses Title, amount, category, date.
Months Grouped sections with totals.
Filters Category, month and search text.
Chart Spending per month.
1 / 2

Step 1: Money is not a Double

0.1 + 0.2 in binary floating point is not exactly 0.3. Over thousands of transactions those tiny errors show up as totals that are off by a cent. The fix is to store integer cents (or use Decimal) and convert only when displaying. A small Money type keeps the rule in one place: nobody can accidentally add a price to a quantity or format it differently on two screens.

The editor below shows the floating-point problem, then a Money type that adds, compares, parses user input like "1,234.5" and formats 123450 as $1,234.50. Parsing is strict on purpose: "12.505" is rejected instead of being silently rounded.

Swift A Money type with parsing and formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In the real app, display uses the system formatter so grouping and symbols follow the user's locale. A Decimal conversion is one line:

Swift
import Foundation

extension Int {
    /// 123450 -> "$1,234.50" (or "1.234,50 $" in another locale)
    func asCurrency(code: String = "USD") -> String {
        (Decimal(self) / 100).formatted(.currency(code: code))
    }
}

The hand-written formatter above exists so the logic is runnable and testable here. In production, prefer the system one, because currencies such as the Japanese yen have no decimals and others use different separators.

Step 2: The model

An expense has an identity (so SwiftUI lists can track it), a title, a Money amount, a category and a date. For grouping, what you need from the date is the year and month, so give that its own small, hashable, sortable type instead of passing strings around.

In the app you would store a real Date and derive the month with Calendar.current.dateComponents([.year, .month], from: date). To keep the examples deterministic, the stand-in below stores plain year/month/day numbers.

Step 3: Filters, groups and totals

Think of the screen as a pipeline: all expenses โ†’ filter โ†’ group by month โ†’ totals โ†’ rows. Each stage is a pure function of its input. That is exactly the SwiftUI mental model from the SwiftUI mental model: the view is a function of state, so you only keep the inputs (expenses and the filter) as state and compute everything else.

A Filter struct holds the selected categories, an optional month and the search text, and answers one question: matches(_ expense:). Adding a new filter later means adding one field and one line.

Grouping uses Dictionary(grouping:by:), then sorts the months newest first. Each group keeps its expenses sorted newest first too. A text bar chart stands in for Swift Charts so you can see the proportions.

Swift Filter, group by month, total and export CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice what the CSV function does. Titles containing commas or quotes are wrapped in double quotes with inner quotes doubled, which is the rule every spreadsheet understands. A title that starts with =, +, - or @ gets a leading apostrophe, because spreadsheet programs may otherwise run it as a formula. That is a real attack on apps that export user-typed text, and it costs one line to prevent.

Step 4: The store

All the state lives in one observable object. It owns the expenses and the filter, exposes the grouped result as a computed property and offers the actions the views call. For observable models the @Observable macro is all you need.

Swift
import Observation

@Observable
final class ExpenseStore {
    var expenses: [Expense] = []
    var filter = Filter()

    var groups: [MonthGroup] {
        let kept = expenses.filter(filter.matches)
        return Dictionary(grouping: kept, by: \.month)
            .map { MonthGroup(month: $0.key, expenses: $0.value.sorted { $0.date > $1.date }) }
            .sorted { $0.month > $1.month }
    }

    func add(_ expense: Expense) { expenses.append(expense) }

    func delete(ids: Set<Expense.ID>) {
        expenses.removeAll { ids.contains($0.id) }
    }
}

Persisting is the same pattern as in the to-do project: make Expense Codable and save the array as JSON, or move to SwiftData when you want queries and relationships.

Step 5: The screens

The list view reads the store from the environment, loops over month groups, and puts each group's total in the section header. ForEach needs stable identities: months are Hashable and expenses are Identifiable, so both work.

Swift
struct ExpenseListView: View {
    @Environment(ExpenseStore.self) private var store
    @State private var showingAdd = false

    var body: some View {
        @Bindable var store = store
        NavigationStack {
            List {
                ForEach(store.groups, id: \.month) { group in
                    Section {
                        ForEach(group.expenses) { expense in
                            ExpenseRow(expense: expense)
                        }
                        .onDelete { offsets in
                            let ids = offsets.map { group.expenses[$0].id }
                            store.delete(ids: Set(ids))
                        }
                    } header: {
                        HStack {
                            Text(group.month.title)
                            Spacer()
                            Text(group.total.cents.asCurrency())
                        }
                    }
                }
            }
            .searchable(text: $store.filter.search)
            .navigationTitle("Expenses")
            .toolbar {
                Button("Add", systemImage: "plus") { showingAdd = true }
            }
            .sheet(isPresented: $showingAdd) { AddExpenseView() }
        }
    }
}

Two details deserve attention. @Bindable var store = store inside body is how you get a $store.filter.search binding from an environment object. And .searchable writes straight into the filter, so the grouping recomputes with no extra code.

The chart view is a thin wrapper over the same grouped data. Because the totals come from store.groups, the chart and the list can never disagree.

Swift
import Charts

struct MonthlyChart: View {
    let groups: [MonthGroup]

    var body: some View {
        Chart(groups, id: \.month) { group in
            BarMark(
                x: .value("Month", group.month.title),
                y: .value("Total", Double(group.total.cents) / 100)
            )
        }
        .frame(height: 180)
        .padding()
    }
}

Exporting uses ShareLink, which accepts a String directly, so the pure csv function from step 3 plugs in without ceremony:

Swift
ShareLink(item: csv(store.groups.flatMap(\.expenses)))

Ideas to extend it

  • Budgets: a per-category monthly limit, with a row turning red when the group total passes it.
  • Recurring expenses: a rule that generates next month's rent, tested as a pure function of a date.
  • Multiple currencies: store the currency code with each amount and never add two different currencies without converting.
  • Receipts: attach a photo with PhotosPicker and store it as a file, with only its name in the model (see UserDefaults, AppStorage and files).
  • Tests: Money(text:), Filter.matches and csv need no UI, so they are the first things to cover in testing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the project store amounts as integer cents instead of Double?

    Values like 0.1 have no exact binary form, so repeated sums can be off by a cent. Integer cents (or Decimal) stay exact.
  2. 2. What is the best way to group expenses by month?

    A calendar month is a year plus a month number. A small Hashable, Comparable type works with Dictionary(grouping:) and sorts correctly across years.
  3. 3. Which values should be stored state in the expense list screen?

    Derived data should be computed, not stored. Keeping only the inputs removes a whole class of out-of-sync bugs.
  4. 4. Why does the CSV exporter prefix a field that starts with = with an apostrophe?

    A cell beginning with =, +, - or @ can be evaluated as a formula when opened. The prefix keeps it as plain text.

Summary

  • Store money as integer cents (or Decimal) in a dedicated type; parse strictly and format at the edge with the system currency formatter.
  • Keep only inputs as state (expenses and filter) and compute groups and totals from them.
  • Model the pipeline as pure functions: filter, group by a YearMonth key, total, then render.
  • One observable store feeds the list, the chart and the export, so they always agree.
  • Escape CSV fields properly and neutralise leading =, +, -, @ to avoid formula injection.
  • Logic that does not import SwiftUI can be run and tested anywhere.

Next: Practice: SwiftUI Exercises