Skip to content
LumenaryAcademy
Professional 70 min

Apps, platforms and a complete project

How Swift apps for Apple devices are built, where else Swift runs, and a finished program that uses the whole course.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From language to product

You now know the Swift language: its types, optionals, closures, protocols, errors, memory model and concurrency. This last lesson looks outward and then inward. Outward: what does it take to turn Swift into an app on someone's phone, and where else is Swift used? Inward: a complete program, written the way an experienced Swift developer would write it, that uses almost everything in the course, followed by the steps to turn it into a tested package.

ExplanationH

Building apps for Apple platforms

Every app for iPhone, iPad, Mac, Apple Watch, Apple TV or Apple Vision Pro is built with Xcode, Apple's development environment, which runs only on macOS. Xcode bundles the Swift toolchain with the platform SDKs, a visual editor, device simulators, a debugger, the Instruments profiler, and the tools to sign and upload apps. To put an app on a real device for a long period or in the App Store, you join the paid Apple Developer Program; you can try your own apps on your own device with a free account.

The user interface is written with one of two frameworks:

  • SwiftUI (introduced in 2019) is declarative: you describe what the screen should look like for the current state, and the framework works out what to redraw when the state changes. It is Apple's recommended choice for new apps and the only framework shared by every Apple platform.
  • UIKit (iOS and iPadOS) and AppKit (macOS) are the older, imperative frameworks, built in Objective-C: you create view objects and change them yourself. A great deal of existing code uses them, and SwiftUI and UIKit can be mixed in one app.

Here is a complete SwiftUI app. It cannot run in this course's Linux checker, because SwiftUI exists only on Apple's systems, so it is shown as plain code:

swift
import SwiftUI

@Observable
final class Counter {
    var taps = 0
}

struct ContentView: View {
    @State private var counter = Counter()

    var body: some View {
        VStack(spacing: 12) {
            Text("Tapped \(counter.taps) times")
                .font(.title)
            Button("Tap me") {
                counter.taps += 1
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

@main
struct CounterApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Everything here is Swift you already know. A view is a struct conforming to the View protocol, with one requirement, body, whose type is some View: an opaque type, because the real type of that VStack of a Text and a Button with modifiers is long and nobody wants to write it. Button("Tap me") { ... } takes its action as a trailing closure. @Observable (a macro from the Observation framework) makes the class report changes to its properties, and @State tells SwiftUI to keep the counter alive across redraws; when taps changes, SwiftUI calls body again and updates only what differs. Views are cheap value types, recreated freely; state lives in a few carefully owned places. @main marks the entry point, as in the package template from the first lesson. SwiftUI views are isolated to the main actor, so the compiler keeps UI code on the main thread.

From there, the path to users goes through testing on simulators and devices, then TestFlight for beta testers, then App Store review, where Apple checks the app against its guidelines before release. Professional teams add continuous integration (Xcode Cloud or another service) that builds and runs the tests on every change, crash reporting, and analytics that respect privacy rules. Two habits separate good apps from the rest: accessibility (SwiftUI views work with VoiceOver, Dynamic Type and other assistive features if you label them well) and localization (Xcode's string catalogs let one app speak many languages). Apple's Human Interface Guidelines describe what users on each platform expect.

ExplanationH

Swift beyond Apple's devices

  • Servers. Frameworks such as Vapor and Hummingbird build web services on SwiftNIO, Apple's open-source networking library. Swift's low memory use and fast start-up suit cloud services, and its concurrency model was designed with servers in mind. The server section of swift.org lists the libraries maintained by the community's server workgroup.
  • Command-line tools. Packages compile to single executables on macOS, Linux and Windows; the Swift Argument Parser package turns a struct into a full command-line interface with help text.
  • Embedded systems. Embedded Swift, a compilation mode still being developed in the open (the 6.4 toolchain still lists it among its experimental features), produces small binaries without the full runtime, for microcontrollers.
  • Interoperability. Swift calls C directly, and since Swift 5.9 can work with many C++ types and functions too, so existing libraries in those languages can be reused, and Swift can be adopted one file at a time in a C++ codebase.
Worked examplesH

The project: splitting the cost of a trip

Example— Who owes whom?

Four friends travel together. Different people pay for dinner, a taxi and museum tickets, sometimes for everyone and sometimes for a few. At the end, each wants to know their balance and the shortest reasonable list of payments that settles everything. The input is a notebook of lines, some of them wrong, as real input always is.

swift
// Trip splitter: who owes whom after a shared trip?

// MARK: - Money

/// An amount of money in cents, so that sums are always exact.
struct Money: Comparable, Sendable, CustomStringConvertible {
    var cents: Int

    static let zero = Money(cents: 0)

    /// Parses "12", "12.5" or "12.50". Returns nil for anything else.
    init?(_ text: Substring) {
        let parts = text.split(separator: ".", omittingEmptySubsequences: false)
        guard (1...2).contains(parts.count), let whole = Int(parts[0]), whole >= 0 else { return nil }
        var fraction = 0
        if parts.count == 2 {
            let digits = parts[1]
            guard (1...2).contains(digits.count), let f = Int(digits) else { return nil }
            fraction = digits.count == 1 ? f * 10 : f
        }
        cents = whole * 100 + fraction
    }

    init(cents: Int) { self.cents = cents }

    static func + (a: Money, b: Money) -> Money { Money(cents: a.cents + b.cents) }
    static func - (a: Money, b: Money) -> Money { Money(cents: a.cents - b.cents) }
    static func < (a: Money, b: Money) -> Bool { a.cents < b.cents }

    var description: String {
        let sign = cents < 0 ? "-" : ""
        let size = abs(cents)
        let rest = size % 100
        return "\(sign)\(size / 100).\(rest < 10 ? "0" : "")\(rest)"
    }

    /// Splits into `count` shares that differ by at most one cent and add up exactly.
    func split(into count: Int) -> [Money] {
        let base = cents / count
        let extra = cents % count
        return (0..<count).map { Money(cents: base + ($0 < extra ? 1 : 0)) }
    }
}

// MARK: - The ledger

enum Entry: Sendable {
    case expense(payer: String, amount: Money, sharedBy: [String], note: String)
    case payment(from: String, to: String, amount: Money)
}

enum ParseError: Error, CustomStringConvertible {
    case unknownCommand(String)
    case unknownPerson(String)
    case badAmount(String)
    case missingFields

    var description: String {
        switch self {
        case .unknownCommand(let word): "unknown command \"\(word)\""
        case .unknownPerson(let name): "unknown person \"\(name)\""
        case .badAmount(let text): "\"\(text)\" is not an amount"
        case .missingFields: "not enough fields"
        }
    }
}

struct Trip {
    private(set) var people: [String] = []
    private(set) var entries: [Entry] = []

    mutating func apply(line: String) throws {
        let words = line.split(separator: " ")
        guard let command = words.first else { return }       // blank line: nothing to do
        switch command {
        case "people":
            people = words.dropFirst().map(String.init)
        case "expense":
            guard words.count >= 5 else { throw ParseError.missingFields }
            let payer = try person(words[1])
            let amount = try money(words[2])
            let sharedBy = words[3] == "all" ? people : try words[3].split(separator: ",").map(person)
            let note = words.dropFirst(4).joined(separator: " ")
            entries.append(.expense(payer: payer, amount: amount, sharedBy: sharedBy, note: note))
        case "pay":
            guard words.count == 4 else { throw ParseError.missingFields }
            entries.append(.payment(from: try person(words[1]), to: try person(words[2]), amount: try money(words[3])))
        default:
            throw ParseError.unknownCommand(String(command))
        }
    }

    private func person(_ word: Substring) throws -> String {
        guard people.contains(String(word)) else { throw ParseError.unknownPerson(String(word)) }
        return String(word)
    }

    private func money(_ word: Substring) throws -> Money {
        guard let amount = Money(word) else { throw ParseError.badAmount(String(word)) }
        return amount
    }

    /// Positive: the group owes this person. Negative: this person owes the group.
    var balances: [String: Money] {
        var result = Dictionary(uniqueKeysWithValues: people.map { ($0, Money.zero) })
        for entry in entries {
            switch entry {
            case let .expense(payer, amount, sharedBy, _):
                result[payer, default: .zero] = result[payer, default: .zero] + amount
                for (person, share) in zip(sharedBy.sorted(), amount.split(into: sharedBy.count)) {
                    result[person, default: .zero] = result[person, default: .zero] - share
                }
            case let .payment(from, to, amount):
                result[from, default: .zero] = result[from, default: .zero] + amount
                result[to, default: .zero] = result[to, default: .zero] - amount
            }
        }
        return result
    }

    /// A short list of transfers that settles every balance: the largest debtor
    /// pays the largest creditor, until everyone is even.
    func settlement() -> [(from: String, to: String, amount: Money)] {
        var owed = balances.filter { $0.value > .zero }.map { (name: $0.key, amount: $0.value) }
        var owing = balances.filter { $0.value < .zero }.map { (name: $0.key, amount: Money.zero - $0.value) }
        var transfers: [(from: String, to: String, amount: Money)] = []
        let byAmount: ((name: String, amount: Money), (name: String, amount: Money)) -> Bool = {
            $0.amount != $1.amount ? $0.amount > $1.amount : $0.name < $1.name
        }
        while !owed.isEmpty && !owing.isEmpty {
            owed.sort(by: byAmount)
            owing.sort(by: byAmount)
            let pay = min(owed[0].amount, owing[0].amount)
            transfers.append((from: owing[0].name, to: owed[0].name, amount: pay))
            owed[0].amount = owed[0].amount - pay
            owing[0].amount = owing[0].amount - pay
            owed.removeAll { $0.amount == .zero }
            owing.removeAll { $0.amount == .zero }
        }
        return transfers
    }
}

// MARK: - Running it

extension String {
    func padded(to width: Int) -> String {
        self + String(repeating: " ", count: max(0, width - count))
    }
}

let notebook = """
people Amara Bao Carmen Dev
expense Amara 120 all Dinner by the river
expense Bao 95.5 Bao,Carmen,Dev Taxi and ferry
pay Carmen Amara 20
expense Dev 30.10 all Museum tickets
expense Zoe 10 all Snacks
expense Bao 12,50 all Coffee
refund Amara 5
"""

var trip = Trip()
for (number, line) in notebook.split(separator: "\n").enumerated() {
    do {
        try trip.apply(line: String(line))
    } catch {
        print("Line \(number + 1) skipped: \(error)")
    }
}

print("\nBalances:")
for (name, amount) in trip.balances.sorted(by: { $0.key < $1.key }) {
    let sign = amount > .zero ? "+" : ""
    print("  \(name.padded(to: 8))\(sign)\(amount)")
}

print("\nTo settle up:")
for t in trip.settlement() {
    print("  \(t.from) pays \(t.to) \(t.amount)")
}
let total = trip.balances.values.reduce(Money.zero, +)
print("\nBalances add up to \(total), as they must.")
text
Line 6 skipped: unknown person "Zoe"
Line 7 skipped: "12,50" is not an amount
Line 8 skipped: unknown command "refund"

Balances:
  Amara   +62.47
  Bao     +26.13
  Carmen  -49.35
  Dev     -39.25

To settle up:
  Carmen pays Amara 49.35
  Dev pays Bao 26.13
  Dev pays Amara 13.12

Balances add up to 0.00, as they must.

Read it as a tour of the course:

  • Money as a type, in cents. Money is a struct around an Int number of cents, so sums are exact, unlike Double (lesson 2). Its failable init? validates text at the boundary (lesson 4); after that, a Money is always valid. It conforms to Comparable, Sendable and CustomStringConvertible, and defines +, - and < as static functions (lesson 7). Its split(into:) spreads the leftover cents so that the shares always add up to the total: 30.10 shared by four is 7.53, 7.53, 7.52 and 7.52, never 7.525.
  • An enum for the ledger. Entry says that a line is an expense or a payment, each with exactly the data it needs (lesson 6). balances switches over it exhaustively; a new kind of entry would not compile until it is handled.
  • Errors with reasons. ParseError is an enum conforming to Error and CustomStringConvertible, so the loop can report why each bad line was skipped and carry on (lesson 8). Small throwing helpers, person(_:) and money(_:), turn validation into one-liners, and try words[3].split(separator: ",").map(person) works because map rethrows.
  • Value semantics throughout. Trip is a struct with private(set) properties and one mutating entry point, so outside code can read the data but change it only by applying a line (lesson 6). There is no class anywhere and so no reference cycle to worry about (lesson 9).
  • Closures and the standard library. filter, map, sorted(by:), reduce, removeAll(where:), zip and enumerated do the bookkeeping (lessons 3 and 5). Dictionaries are sorted before printing, so the output is the same on every run.
  • An honest algorithm. The settlement is greedy: the person who owes most pays the person who is owed most, as much as possible, and repeat. Each transfer settles at least one person, so it never needs more transfers than people minus one. It does not always find the very fewest possible transfers; that version of the problem is much harder, and for a group of friends, the greedy answer is what people actually use.

One last detail: the comments starting with // MARK: - are understood by Xcode and other editors, which show them as section headings in the file's outline.

ComputationC

Checking a claim with code

The walkthrough said the greedy settlement "does not always find the very fewest possible transfers". A professional does not leave a claim like that unsupported, and a short program can settle it. The true minimum has a neat characterization: if the group can be split into g separate subgroups whose balances each add up to zero, each subgroup of k people can settle in k − 1 transfers, so n people need n − g transfers, and the best plan uses the largest possible g. For a handful of people we can simply try every subset:

swift
// Is "largest debtor pays largest creditor" always the shortest way to settle?
// Compare it with the true minimum on one small example.

/// The greedy settlement from the project, on whole units, ties broken by name.
func greedyTransfers(_ balances: [String: Int]) -> [String] {
    var owed = balances.filter { $0.value > 0 }.map { (name: $0.key, amount: $0.value) }
    var owing = balances.filter { $0.value < 0 }.map { (name: $0.key, amount: -$0.value) }
    var transfers: [String] = []
    while !owed.isEmpty && !owing.isEmpty {
        owed.sort { $0.amount != $1.amount ? $0.amount > $1.amount : $0.name < $1.name }
        owing.sort { $0.amount != $1.amount ? $0.amount > $1.amount : $0.name < $1.name }
        let pay = min(owed[0].amount, owing[0].amount)
        transfers.append("\(owing[0].name)→\(owed[0].name) \(pay)")
        owed[0].amount -= pay
        owing[0].amount -= pay
        owed.removeAll { $0.amount == 0 }
        owing.removeAll { $0.amount == 0 }
    }
    return transfers
}

/// The true minimum: n people need n − g transfers, where g is the largest number
/// of separate groups whose balances each add up to zero. Tries every subset.
func minimumTransfers(_ amounts: [Int]) -> Int {
    let n = amounts.count
    var sum = [Int](repeating: 0, count: 1 << n)
    var groups = [Int](repeating: 0, count: 1 << n)
    for mask in 1..<(1 << n) {
        let lowest = mask.trailingZeroBitCount
        sum[mask] = sum[mask & ~(1 << lowest)] + amounts[lowest]
        var best = 0
        for i in 0..<n where mask & (1 << i) != 0 {
            best = max(best, groups[mask & ~(1 << i)])
        }
        groups[mask] = best + (sum[mask] == 0 ? 1 : 0)
    }
    return n - groups[(1 << n) - 1]
}

let balances = ["Ana": 3, "Ben": 4, "Chidi": -3, "Dina": -2, "Eitan": -2]
let greedy = greedyTransfers(balances)
print("greedy:", greedy.count, "transfers:", greedy.joined(separator: ", "))
print("minimum possible:", minimumTransfers(Array(balances.values)))
text
greedy: 4 transfers: Chidi→Ben 3, Dina→Ana 2, Eitan→Ana 1, Eitan→Ben 1
minimum possible: 3

Greedy starts by matching the two largest amounts, Ben's 4 and Chidi's 3, and that leaves crumbs to clean up. The optimal plan notices that Ana (+3) and Chidi (−3) cancel exactly, and so do Ben (+4) with Dina and Eitan (−2 each): two zero-sum groups, so 5 − 2 = 3 transfers. The exhaustive method takes time proportional to 2 to the power n times n, fine for a dinner party and hopeless for a city; the general problem is NP-hard, which is why real apps use a greedy rule and accept the occasional extra transfer. The code uses bit masks for subsets (1 << n is 2 to the power n, and trailingZeroBitCount finds the lowest member), a typical trick in Swift as in C. Notice also that Array(balances.values) comes out in an unpredictable order, which is harmless here because the minimum does not depend on order, and that is precisely why the program prints only the count, not the dictionary.

ComputationC

From one file to a tested package

A single file is right for a lesson, but a real tool would be a package with three targets: a library with the logic, a small executable that uses it, and tests.

swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "TripSplitter",
    targets: [
        .target(name: "TripKit"),
        .executableTarget(name: "trip", dependencies: ["TripKit"]),
        .testTarget(name: "TripKitTests", dependencies: ["TripKit"]),
    ]
)

Move everything above // MARK: - Running it into Sources/TripKit/TripKit.swift and the rest into Sources/trip/main.swift, starting with import TripKit. The first build fails, and the two errors are worth meeting on purpose:

  • cannot find 'Trip' in scope: declarations are internal by default, visible only inside their own module. The types and members that main.swift uses must be marked public, and Trip needs a public init() {}, because the memberwise and default initializers are never public. Deciding what is public is deciding your module's API.
  • static property 'zero' is not concurrency-safe because non-'Sendable' type 'Money' may have shared mutable state: this package uses the Swift 6 language mode, and Swift infers Sendable only for non-public types. Once Money is public it must declare Sendable itself, as the single-file version already does.

Then add tests in Tests/TripKitTests/:

swift
import Testing
@testable import TripKit

@Test(arguments: [("12", 1200), ("12.5", 1250), ("0.05", 5)])
func parsesMoney(text: String, cents: Int) throws {
    let money = try #require(Money(Substring(text)))
    #expect(money.cents == cents)
}

@Test func sharesAddUpExactly() {
    let shares = Money(cents: 1001).split(into: 3)
    #expect(shares.map(\.cents) == [334, 334, 333])
}

@Test func settlementClearsEveryBalance() throws {
    var trip = Trip()
    try trip.apply(line: "people Ana Ben")
    try trip.apply(line: "expense Ana 10 all Lunch")
    let transfers = trip.settlement()
    #expect(transfers.count == 1)
    #expect(transfers.first?.from == "Ben")
    #expect(transfers.first?.amount == Money(cents: 500))
}

swift test ended with:

text
✔ Test sharesAddUpExactly() passed after 0.001 seconds.
✔ Test settlementClearsEveryBalance() passed after 0.001 seconds.
✔ Test parsesMoney(text:cents:) with 3 test cases passed after 0.001 seconds.
✔ Test run with 3 tests in 0 suites passed after 0.001 seconds.

and swift run trip printed the same report as above. Natural next steps: read the notebook from a file named on the command line with Swift Argument Parser, support several currencies with an enum, and write a SwiftUI front end on top of the same TripKit library, which is exactly why the logic lives in a library of its own.

Further reading

Where to go next

  • The Swift Programming Language at docs.swift.org is the official book. Having finished this course, read its Language Guide straight through: it will feel like a review with many new details, and its Language Reference is the closest thing Swift has to a formal specification.
  • Apple's SwiftUI tutorials at developer.apple.com/tutorials/swiftui build complete apps step by step, if you have a Mac.
  • The Swift Forums at forums.swift.org are where the language is designed in public. Reading the pitches and reviews for a few proposals is the best way to understand why Swift is the way it is.
  • The Swift Package Index shows what the community has built; reading the source of a popular, well-tested package is an education in professional style.
  • Contribute. The compiler, standard library, Foundation, SwiftPM and Swift Testing are all open source on GitHub under the swiftlang organization, with issues labelled for newcomers.
ExplanationH

A closing thought

Optional Christian reflection · Making the right path the easy one

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

Swift's designers repeatedly chose to make the safe thing the easy thing: let is shorter to justify than var, handling nil is easier than forcing it, an exhaustive switch costs nothing until the day it saves you. Many traditions of wisdom, Christian ones among them, notice the same about character: good habits are built less by heroic effort in the moment than by arranging life so that the right choice is the natural one. A language cannot make a programmer careful, but it can be a patient teacher, and so can we, for the people who will one day read and maintain our code.

Exercises

Exercises

1. Apps, platforms and a complete project

CoreHuman

A SwiftUI view declares var body: some View. Why some View rather than the exact type of the VStack it returns?

Choose one

2. Apps, platforms and a complete project

CoreComputational

Using the project's Money type, what does this line print?

print(Money(cents: -5), Money(cents: 1234))

3. Apps, platforms and a complete project

CoreComputational

What does print(Money(cents: 100).split(into: 3).map(\.cents)) print?

4. Apps, platforms and a complete project

CoreComputational

What does this line print?

print(Money("7.5")?.cents ?? -1, Money("7.123")?.cents ?? -1)

5. Apps, platforms and a complete project

StretchHuman

After moving Trip into the TripKit library and marking the struct public, main.swift still cannot write var trip = Trip(). Why does the library need an explicit public init() {}?

Choose one

6. Apps, platforms and a complete project

Warm-upHuman

Which of these are available only on Apple's operating systems? List the letters.

  • A. SwiftUI
  • B. Swift Package Manager
  • C. Xcode
  • D. UIKit
  • E. Swift Testing
  • F. Vapor

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

7. Apps, platforms and a complete project

StretchHuman

Six friends end a trip, and every one of them has a non-zero balance. At most how many transfers can the project's greedy settlement produce?

Further reading and resources