Data-driven apps with SwiftUI
Apps whose screens follow a changing model: macros, the @Observable model and how SwiftUI tracks what a view reads, lists with search, navigation, charts with Swift Charts, and loading data asynchronously.
- CS61B
- For Project 4: NGordNet
- Swift book
- Macros · Properties
- Documentation
- Observable() · List · NavigationStack · Swift Charts
Lesson 26’s views owned small pieces of state with @State. Project 9 needs
more: a collection of word histories loaded from files, a list you can search,
a screen for each word, and charts of how often words were used over two
centuries. This lesson covers the SwiftUI for that kind of app, in which one
model holds the data, and many views show parts of it and stay up to date
by themselves.
Macros
This lesson’s central tool is written @Observable, and it is a macro. The
Swift book’s chapter on macros describes them: code that runs at compile
time to generate more code, which is then compiled as if you had written it.
- A freestanding macro stands on its own and starts with
#. You have used#expect(Lesson 23),#Preview(Lesson 26), and#lineis a built-in relative. - An attached macro starts with
@and modifies the declaration it is attached to, adding members, conformances, or code around properties.
Macros are ordinary Swift packages that transform the syntax tree of your code. The expansion is type-checked like any other code, and in Xcode you can right-click a macro and choose Expand Macro to see exactly what it generates. Writing your own macro is beyond this course; using them well requires only knowing what they expand to.
Observable models
A model is usually a class, because many views share it. Marking it with the
@Observable macro makes SwiftUI track which properties each view reads,
and update exactly those views when those properties change:
import Observation
@Observable
final class WordLibrary {
var words = ["swift", "sparrow", "owl"]
var searchText = ""
var visibleWords: [String] {
searchText.isEmpty ? words : words.filter { $0.contains(searchText) }
}
}
let library = WordLibrary()
var changes = 0
func watch() {
withObservationTracking {
_ = library.visibleWords // reads words and searchText
} onChange: {
changes += 1
}
}
watch()
library.searchText = "sw" // a tracked property changed
watch()
library.words.append("swan") // so did this one
print(changes, library.visibleWords) // 2 ["swift", "swan"]
withObservationTracking is the mechanism SwiftUI itself uses, shown here
without SwiftUI. It runs the first closure and records every observable
property it reads, even through a computed property like visibleWords. When
any of them changes, onChange runs once, and tracking ends, which is why
watch() is called again. SwiftUI does the same with each view’s body: it
records what the body reads, and when something changes, it computes the body
again, which records the new set of dependencies.
What the @Observable macro generates is the bookkeeping: each stored property
becomes a computed property whose getter reports “read” and whose setter reports
“changed”, plus a hidden registrar that tracks them. The class also conforms to
the Observable protocol.
Sharing a model with views
A view that creates a model owns it with @State, as with any other state.
Views that only use it can take it as a plain property, or find it in the
environment, a set of values that SwiftUI passes down the view hierarchy:
import SwiftUI
@Observable
final class WordLibrary {
var words = ["swift", "sparrow", "owl"]
var searchText = ""
var visibleWords: [String] {
searchText.isEmpty ? words : words.filter { $0.localizedStandardContains(searchText) }
}
}
struct LibraryScreen: View {
@State private var library = WordLibrary() // this view owns the model
var body: some View {
WordList()
.environment(library) // available to everything below
}
}
struct WordList: View {
@Environment(WordLibrary.self) private var library
var body: some View {
@Bindable var library = library // for the $ binding below
List(library.visibleWords, id: \.self) { word in
Text(word)
}
.searchable(text: $library.searchText)
}
}
@Bindable makes bindings, the $ projections from Lesson 26, to the
properties of an observable object that the view did not create. Here
.searchable needs a binding to searchText, so that typing in the search
field changes the model; the list reads visibleWords, so it updates as you
type.
Lists and navigation
List shows rows, and ForEach makes one view per item of a collection. Both
need to tell items apart across updates, so that SwiftUI can animate insertions
and keep selection right: either id: \.self for values that are their own
identity, or items that conform to Identifiable, with an id property.
NavigationStack pushes screens: a NavigationLink(value:) in a list row, and a
.navigationDestination(for:) that says which view shows a value of that type:
import SwiftUI
struct Word: Identifiable, Hashable {
let text: String
let counts: [Int: Int] // year → number of uses
var id: String { text }
}
struct WordsScreen: View {
let words: [Word]
var body: some View {
NavigationStack {
List(words) { word in
NavigationLink(word.text, value: word)
}
.navigationTitle("Words")
.navigationDestination(for: Word.self) { word in
Text("\(word.text): \(word.counts.values.reduce(0, +)) uses")
.navigationTitle(word.text)
}
}
}
}
Navigating by value keeps the navigation state as data: a path of values that the program can inspect, change, or save, like any other state.
Charts
Swift Charts draws charts from data, declaratively, in the same style as views. A chart is a set of marks, each mapping values to visual positions:
import Charts
import SwiftUI
struct YearCount: Identifiable {
let year: Int
let count: Int
var id: Int { year }
}
struct HistoryChart: View {
let word: String
let points: [YearCount]
var body: some View {
Chart(points) { point in
LineMark(
x: .value("Year", point.year),
y: .value("Uses", point.count)
)
.foregroundStyle(by: .value("Word", word))
}
.chartXAxisLabel("Year")
.chartYAxisLabel("Uses per million words")
.frame(minHeight: 240)
}
}
LineMark connects the points; BarMark, PointMark, and AreaMark draw the same
data in other ways. .value("Year", …) names each dimension, which labels the
axes and the legend. Coloring by word means several words’ lines can share one
chart, each in its own color, with a legend generated automatically, which
Project 9 uses to compare words.
Loading data
Real data arrives from files or the network, and loading takes time. The model records where loading has got to, with Lesson 19’s favorite tool, an enum:
import SwiftUI
enum Loading<Value> {
case loading
case loaded(Value)
case failed(String)
}
struct LoadingView: View {
@State private var state: Loading<[String]> = .loading
var body: some View {
Group {
switch state {
case .loading:
ProgressView("Loading words…")
case .loaded(let words):
List(words, id: \.self) { Text($0) }
case .failed(let message):
ContentUnavailableView("Could not load words", systemImage: "exclamationmark.triangle",
description: Text(message))
}
}
.task {
do {
try await Task.sleep(for: .milliseconds(300)) // stand-in for reading a file
state = .loaded(["swift", "sparrow", "owl"])
} catch {
state = .failed("cancelled")
}
}
}
}
The view’s body is a switch over the state, so every situation has a screen,
and the compiler checks that none is forgotten. .task starts loading when the
view appears and cancels it if the view goes away, as in Lesson 26.
Put the lines in order
Put the lines in order so the program prints 1.
var value = 0}@Observable final class Counter {var changes = counter.valuecounter.value = 5import ObservationwithObservationTracking { _ = counter.value } onChange: { changes += 1 }let counter = Counter()print(changes)
Show the correct program
import Observation
@Observable final class Counter {
var value = 0
}
let counter = Counter()
var changes = counter.value
withObservationTracking { _ = counter.value } onChange: { changes += 1 }
counter.value = 5
print(changes)Lab 41: Data-driven apps
The model problems run as scripts. The SwiftUI problems need a Mac; put them in an app package as in Lesson 26.
Q0: What would Swift print?
What would Swift print?
import Observation
@Observable final class Settings {
var volume = 5
var theme = "light"
}
let settings = Settings()
var changes = 0
withObservationTracking {
_ = settings.volume
} onChange: {
changes += 1
}
settings.theme = "dark"
settings.volume = 7
settings.volume = 9
print(changes)Show answer and explanation
Answer1
The tracked closure read only volume, so changing theme does not count.
Changing volume fires onChange once, and ends the tracking, so the second
change is not reported. SwiftUI re-registers after each update; code using
withObservationTracking directly must do the same.
Q1: A model with derived data
Write an @Observable class WordHistory holding a dictionary from word to its
yearly counts ([String: [Int: Int]]), a selected set of words, and computed
properties totalUses(of:) and selectedSeries, which returns, for each selected
word in alphabetical order, its (year, count) pairs sorted by year. Check with
withObservationTracking that reading selectedSeries tracks selected.
Show solution
import Observation
@Observable
final class WordHistory {
var counts: [String: [Int: Int]] = [:]
var selected: Set<String> = []
func totalUses(of word: String) -> Int {
counts[word, default: [:]].values.reduce(0, +)
}
var selectedSeries: [(word: String, points: [(year: Int, count: Int)])] {
selected.sorted().map { word in
let points = counts[word, default: [:]].sorted { $0.key < $1.key }.map { (year: $0.key, count: $0.value) }
return (word, points)
}
}
}
let history = WordHistory()
history.counts = ["swift": [2000: 3, 1990: 1], "owl": [1990: 5]]
history.selected = ["swift"]
var changed = false
withObservationTracking {
_ = history.selectedSeries
} onChange: {
changed = true
}
history.selected.insert("owl")
assert(changed)
assert(history.totalUses(of: "swift") == 4)
assert(history.selectedSeries.map(\.word) == ["owl", "swift"])
assert(history.selectedSeries[1].points.map(\.year) == [1990, 2000])Derived data belongs in computed properties, not in stored copies that would
have to be kept in sync. Observation sees through them: reading selectedSeries
reads selected and counts, and a change to either is reported.
Q2: A searchable list
Write a view that shows the words of a WordHistory-like model in a searchable
list, each row showing the word and its total uses, sorted by total uses, most
first.
Show solution
import SwiftUI
@Observable
final class WordStore {
var totals: [String: Int] = ["swift": 40, "owl": 12, "sparrow": 25]
var searchText = ""
var rows: [(word: String, total: Int)] {
totals
.filter { searchText.isEmpty || $0.key.localizedStandardContains(searchText) }
.sorted { $0.value > $1.value }
.map { (word: $0.key, total: $0.value) }
}
}
struct SearchableWords: View {
@State private var store = WordStore()
var body: some View {
NavigationStack {
List(store.rows, id: \.word) { row in
LabeledContent(row.word, value: row.total, format: .number)
}
.navigationTitle("Words")
.searchable(text: $store.searchText)
}
}
}LabeledContent lays out a label and a value the way the platform expects,
and format: .number formats the count for the user’s locale. Because this view
owns the store with @State, $store.searchText works without @Bindable.
Q3: A chart of several words
Write a view that charts the yearly counts of several words at once, one
colored line per word, with points marked, given
[(word: String, points: [(year: Int, count: Int)])].
Show solution
import Charts
import SwiftUI
struct MultiWordChart: View {
let series: [(word: String, points: [(year: Int, count: Int)])]
var body: some View {
Chart {
ForEach(series, id: \.word) { item in
ForEach(item.points, id: \.year) { point in
LineMark(x: .value("Year", point.year), y: .value("Uses", point.count))
.foregroundStyle(by: .value("Word", item.word))
PointMark(x: .value("Year", point.year), y: .value("Uses", point.count))
.foregroundStyle(by: .value("Word", item.word))
}
}
}
.chartLegend(position: .bottom)
.frame(minHeight: 260)
}
}Grouping by .foregroundStyle(by:) does two things: each word gets its own
color, and the line marks with the same word are connected into one line rather
than all points into a single zigzag.
Q4: Loading with failure
Write a model with a Loading<[String: Int]> state and an async method load()
that sleeps briefly and then either fills the state or, if a flag says so, fails
with a message. Write a view that shows each state and a Retry button on failure.
Show solution
import SwiftUI
enum Loading<Value> {
case loading
case loaded(Value)
case failed(String)
}
@Observable
final class Loader {
var state: Loading<[String: Int]> = .loading
var shouldFail = true
func load() async {
state = .loading
try? await Task.sleep(for: .milliseconds(200))
if shouldFail {
shouldFail = false // succeed next time
state = .failed("the data file is missing")
} else {
state = .loaded(["swift": 40, "owl": 12])
}
}
}
struct LoaderView: View {
@State private var loader = Loader()
var body: some View {
Group {
switch loader.state {
case .loading:
ProgressView()
case .loaded(let totals):
List(totals.sorted { $0.key < $1.key }, id: \.key) { entry in
LabeledContent(entry.key, value: entry.value, format: .number)
}
case .failed(let message):
VStack {
Text(message)
Button("Retry") { Task { await loader.load() } }
.buttonStyle(.glassProminent)
}
}
}
.task { await loader.load() }
}
}Putting the loading logic in the model keeps the view a pure description of the state, and makes the logic testable with Swift Testing, without a window.
What’s next
Next lesson: graphs, the most general way to represent connections, and the traversals that explore them.