Swift Mini Project: Budget Manager
Let's put the whole course together and build a small budget manager step by step. It records income and expenses, validates input, prints a report grouped by category, warns about overspending and saves everything as JSON. Each step is a complete program you can run and modify.
| Step | Feature | Swift topics |
|---|---|---|
| 1 | Model the data | enums, structs, computed properties |
| 2 | A budget that stores transactions | mutating methods, arrays, reduce |
| 3 | Validation | errors, throws, guard |
| 4 | Category report | dictionaries, Dictionary(grouping:), sorting, formatting |
| 5 | Spending limits | optionals, protocols, extensions |
| 6 | Save & load | Codable, JSON |
| 7 | An iPhone screen | SwiftUI (preview) |
Step 1: Model the data
A transaction has a title, an amount in cents (integers avoid floating-point rounding errors with money), a kind and a category.
enum Kind: String {
case income, expense
}
enum Category: String, CaseIterable {
case salary, food, rent, transport, fun
}
struct Transaction {
let title: String
let cents: Int
let kind: Kind
let category: Category
// Positive for income, negative for expenses
var signedCents: Int { kind == .income ? cents : -cents }
}
func money(_ cents: Int) -> String {
let sign = cents < 0 ? "-" : ""
let value = abs(cents)
let fraction = value % 100
return "\(sign)$\(value / 100).\(fraction < 10 ? "0" : "")\(fraction)"
}
let coffee = Transaction(title: "Coffee", cents: 450, kind: .expense, category: .food)
let pay = Transaction(title: "Paycheck", cents: 250_000, kind: .income, category: .salary)
print(coffee.title, money(coffee.signedCents))
print(pay.title, money(pay.signedCents))
print("Categories:", Category.allCases.map(\.rawValue))Coffee -$4.50
Paycheck $2500.00
Categories: ["salary", "food", "rent", "transport", "fun"]
Step 2: A budget that stores transactions
The Budget struct owns an array of transactions. Adding one changes the struct, so the method must be mutating.
enum Kind { case income, expense }
enum Category: String { case salary, food, rent, transport, fun }
struct Transaction {
let title: String
let cents: Int
let kind: Kind
let category: Category
var signedCents: Int { kind == .income ? cents : -cents }
}
struct Budget {
private(set) var transactions: [Transaction] = []
mutating func add(_ title: String, _ cents: Int, _ kind: Kind, _ category: Category) {
transactions.append(Transaction(title: title, cents: cents, kind: kind, category: category))
}
var balance: Int { transactions.reduce(0) { $0 + $1.signedCents } }
var totalExpenses: Int {
transactions.filter { $0.kind == .expense }.reduce(0) { $0 + $1.cents }
}
}
var budget = Budget()
budget.add("Paycheck", 250_000, .income, .salary)
budget.add("Rent", 120_000, .expense, .rent)
budget.add("Groceries", 8_640, .expense, .food)
budget.add("Bus pass", 4_500, .expense, .transport)
print("Transactions:", budget.transactions.count)
print("Spent:", budget.totalExpenses, "cents")
print("Balance:", budget.balance, "cents")Transactions: 4
Spent: 133140 cents
Balance: 116860 cents
Tip:
private(set)lets everyone readtransactionsbut only the budget itself can change it — no one can bypassadd.
Step 3: Validation with errors
Bad input should be rejected. add now throws a descriptive error for empty titles or non-positive amounts.
enum Kind { case income, expense }
enum Category: String { case salary, food, rent, transport, fun }
struct Transaction {
let title: String
let cents: Int
let kind: Kind
let category: Category
}
enum BudgetError: Error, CustomStringConvertible {
case emptyTitle
case invalidAmount(Int)
var description: String {
switch self {
case .emptyTitle: return "A title is required"
case .invalidAmount(let c): return "Amount must be positive (got \(c))"
}
}
}
struct Budget {
private(set) var transactions: [Transaction] = []
mutating func add(_ title: String, _ cents: Int, _ kind: Kind, _ category: Category) throws {
guard !title.isEmpty else { throw BudgetError.emptyTitle }
guard cents > 0 else { throw BudgetError.invalidAmount(cents) }
transactions.append(Transaction(title: title, cents: cents, kind: kind, category: category))
}
}
var budget = Budget()
let inputs: [(String, Int)] = [("Cinema", 1_200), ("", 500), ("Refund?", -300), ("Pizza", 1_850)]
for (title, cents) in inputs {
do {
try budget.add(title, cents, .expense, .fun)
print("✓ added \(title)")
} catch {
print("✗ \(error)")
}
}
print("Stored:", budget.transactions.map(\.title))✓ added Cinema
✗ A title is required
✗ Amount must be positive (got -300)
✓ added Pizza
Stored: ["Cinema", "Pizza"]
Step 4: A category report
Dictionary(grouping:by:) groups transactions by category. Dictionary order is random, so we sort before printing, and padding(toLength:withPad:startingAt:) plus String(format:) line up the columns.
import Foundation
enum Category: String { case food, rent, transport, fun }
struct Expense {
let title: String
let cents: Int
let category: Category
}
let expenses = [
Expense(title: "Rent", cents: 120_000, category: .rent),
Expense(title: "Groceries", cents: 8_640, category: .food),
Expense(title: "Bus pass", cents: 4_500, category: .transport),
Expense(title: "Lunch", cents: 1_390, category: .food),
Expense(title: "Concert", cents: 6_500, category: .fun),
Expense(title: "Taxi", cents: 2_250, category: .transport),
]
let groups = Dictionary(grouping: expenses, by: \.category)
let totals = groups.mapValues { $0.reduce(0) { $0 + $1.cents } }
let grandTotal = totals.values.reduce(0, +)
print("Category Amount Share")
for (category, cents) in totals.sorted(by: { $0.value > $1.value }) {
let share = Double(cents) / Double(grandTotal) * 100
let name = category.rawValue.padding(toLength: 10, withPad: " ", startingAt: 0)
print(name + String(format: " %8.2f %6.1f%%", Double(cents) / 100, share))
}
print("TOTAL " + String(format: " %8.2f", Double(grandTotal) / 100))Category Amount Share
rent 1200.00 83.8%
food 100.30 7.0%
transport 67.50 4.7%
fun 65.00 4.5%
TOTAL 1432.80
Step 5: Spending limits
Some categories get a monthly limit. A dictionary lookup returns an optional (not every category has a limit), and a protocol plus extension adds a reusable "status" helper.
enum Category: String, CaseIterable { case food, rent, transport, fun }
protocol Limited {
var spent: Int { get }
var limit: Int? { get }
}
extension Limited {
var status: String {
guard let limit else { return "no limit" }
let percent = spent * 100 / limit
switch percent {
case ..<75: return "OK (\(percent)%)"
case 75..<100: return "Careful (\(percent)%)"
default: return "OVER by \(spent - limit) cents"
}
}
}
struct CategoryStatus: Limited {
let category: Category
let spent: Int
let limit: Int?
}
let spent: [Category: Int] = [.food: 10_030, .rent: 120_000, .transport: 6_750, .fun: 6_500]
let limits: [Category: Int] = [.food: 12_000, .transport: 6_000, .fun: 8_000]
for category in Category.allCases {
let s = CategoryStatus(category: category, spent: spent[category] ?? 0, limit: limits[category])
print("\(category.rawValue): \(s.status)")
}food: Careful (83%)
rent: no limit
transport: OVER by 750 cents
fun: Careful (81%)
Iterating Category.allCases (an array) instead of the dictionary keeps the order stable.
Step 6: Save and load as JSON
Make the model Codable and the whole budget can be written to JSON and read back — the basis for saving to a file or syncing with a server.
import Foundation
enum Kind: String, Codable { case income, expense }
struct Transaction: Codable, Equatable {
let title: String
let cents: Int
let kind: Kind
}
struct Budget: Codable, Equatable {
var owner: String
var transactions: [Transaction]
var balance: Int {
transactions.reduce(0) { $0 + ($1.kind == .income ? $1.cents : -$1.cents) }
}
}
let budget = Budget(owner: "Sam", transactions: [
Transaction(title: "Paycheck", cents: 250_000, kind: .income),
Transaction(title: "Rent", cents: 120_000, kind: .expense),
])
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(budget)
print(String(data: data, encoding: .utf8)!)
let loaded = try JSONDecoder().decode(Budget.self, from: data)
print("Loaded \(loaded.owner)'s budget, balance \(loaded.balance) cents")
print("Identical after round trip:", loaded == budget){
"owner" : "Sam",
"transactions" : [
{
"cents" : 250000,
"kind" : "income",
"title" : "Paycheck"
},
{
"cents" : 120000,
"kind" : "expense",
"title" : "Rent"
}
]
}
Loaded Sam's budget, balance 130000 cents
Identical after round trip: true
Notice that the computed balance is not saved — only stored properties are encoded.
Note: In an iOS app you would write
datato a file withtry data.write(to: url)and read it back withData(contentsOf: url).
Step 7: Put it on an iPhone
With the model done, a SwiftUI screen is only a few lines. (SwiftUI can't run here, so the code is followed by an HTML mock.)
import SwiftUI
struct BudgetView: View {
@State private var budget = Budget.sample
var body: some View {
NavigationStack {
List {
Section {
Text(money(budget.balance))
.font(.largeTitle.bold())
} header: { Text("Balance") }
Section("Transactions") {
ForEach(budget.transactions, id: \.title) { t in
HStack {
Text(t.title)
Spacer()
Text(money(t.signedCents))
.foregroundStyle(t.kind == .income ? .green : .primary)
}
}
}
}
.navigationTitle("Budget")
}
}
}<div style="width:320px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#f2f2f7;font-family:-apple-system,system-ui,sans-serif;padding:48px 0 32px">
<div style="font-size:30px;font-weight:700;padding:0 16px 12px">Budget</div>
<div style="font-size:13px;color:#8e8e93;padding:6px 32px">BALANCE</div>
<div style="margin:0 16px 20px;background:#fff;border-radius:10px;padding:12px 16px;font-size:30px;font-weight:700">$1168.60</div>
<div style="font-size:13px;color:#8e8e93;padding:6px 32px">TRANSACTIONS</div>
<div style="margin:0 16px;background:#fff;border-radius:10px;font-size:17px">
<div style="display:flex;justify-content:space-between;padding:11px 16px"><span>Paycheck</span><span style="color:#34c759">$2500.00</span></div>
<div style="display:flex;justify-content:space-between;padding:11px 16px;border-top:1px solid #e5e5ea"><span>Rent</span><span>-$1200.00</span></div>
<div style="display:flex;justify-content:space-between;padding:11px 16px;border-top:1px solid #e5e5ea"><span>Groceries</span><span>-$86.40</span></div>
<div style="display:flex;justify-content:space-between;padding:11px 16px;border-top:1px solid #e5e5ea"><span>Bus pass</span><span>-$45.00</span></div>
</div>
</div>Ideas to extend the project
- Add a
datefield (as aStringlike"2025-03-14") and filter transactions by month. - Support recurring transactions with an enum case that has an associated value:
case monthly(day: Int). - Turn
Budgetinto anactorand add transactions from several tasks concurrently. - Add an "Add transaction" form in SwiftUI with
TextField,Pickerand a@Statedraft.
Test yourself
Why does the project store money as integer cents instead of Double dollars?
- Int is faster to print
- Double can't be negative
- Integers avoid floating-point rounding errors with money
- JSON doesn't support decimals
Why must Budget.add be marked mutating?
- Because it throws
- Because Budget is a struct and the method changes its stored property
- Because it is private
- Because arrays are reference types
Which properties of a Codable struct end up in the JSON?
- All properties, including computed ones
- Only stored properties
- Only
letproperties - Only optional properties