Swift & SwiftUI course › Session 5
Lists, observation and environment
Scrolling lists with sections, editing, swipe actions and search; tree data; and how iOS 17's Observation framework shares a model between views, compared with the older ObservableObject API that exams still ask about.
About 40 minutes · covers List, DisclosureGroup, OutlineGroup, @Observable, @Bindable, @Environment
Open the interactive lesson (live previews, quizzes) →What you'll learn
- Build static and dynamic Lists from Identifiable data, with sections and list styles
- Add delete, move, swipe actions, search and pull to refresh
- Show tree data with DisclosureGroup, OutlineGroup and
List(children:) - Share a model with @Observable, @State, @Bindable and @Environment
- Compare Observation with ObservableObject, @StateObject, @ObservedObject and @EnvironmentObject
Contents
- List basics
- Delete, move and swipe actions
- Search and refresh
- DisclosureGroup, OutlineGroup and tree data
- Observation: @Observable, @State, @Bindable
- Seeing what redraws: _printChanges and tracking
- @Environment
- ObservableObject: the older API
- Bug hunt: Observation
List basics
List shows rows in a scrolling, system-styled table. It loads rows lazily, so it handles thousands of items. Rows can be static (written out) or dynamic (built from a collection).
// Static rows
List {
Text("Wi-Fi")
Text("Bluetooth")
Label("Battery", systemImage: "battery.100")
}
// Dynamic rows from Identifiable data
struct Student: Identifiable {
let id = UUID()
var name: String
}
List(students) { student in
Text(student.name)
}
// Values without an id: use the value itself as the id
List(["Asha", "Ravi", "Meera"], id: \.self) { name in
Text(name)
}SwiftUI must know which row is which to animate inserts and deletes and keep state attached to the right row. It gets that from Identifiable (a property called id) or from an explicit id: key path.
struct Student: Identifiable {
let id: Int
var name: String
}
let students = [
Student(id: 1, name: "Asha"),
Student(id: 2, name: "Ravi"),
Student(id: 3, name: "Asha"), // same name, different student
]
print(students.map { $0.id })
let names = students.map { $0.name }
print(names.count, Set(names).count) // with id: \.self two rows share an idOutput
[1, 2, 3]
3 2Sections, ForEach and list styles
ForEach inside a List to mix sections, static rows and dynamic rows.List {
Section("Toppers") {
ForEach(toppers) { student in
Text(student.name)
}
}
Section {
ForEach(others) { student in
Text(student.name)
}
} header: {
Text("Others")
} footer: {
Text("\(others.count) students")
}
}
.listStyle(.insetGrouped)| List style | Looks like |
|---|---|
.automatic | The default: the system picks a style for the context |
.plain | Edge-to-edge rows, no grouped background |
.grouped | Grey background, sections as full-width blocks |
.insetGrouped | Rounded section cards with margins: the Settings look |
.inset | Plain rows with side margins |
.sidebar | Collapsible sections, for a sidebar in a split view |
List(items) { } | ForEach(items) { } | |
|---|---|---|
| What it is | A scrolling container with rows | A view builder that repeats content; no scrolling or style |
| Mix static and dynamic rows | No (use List { ForEach }) | Yes, inside a List, VStack or Section |
onDelete / onMove | Not available | Available |
Trap: an id key path that isn't unique
struct Club {
var name: String
var members: Int
}
let clubs = [
Club(name: "Chess", members: 12),
Club(name: "Robotics", members: 30),
Club(name: "Chess", members: 5), // a second club with the same name
]
List(clubs, id: \.name) { club in // two rows claim the id "Chess"
Text("\(club.name): \(club.members)")
}id: \.name promises SwiftUI that no two clubs share a name. The compiler can't check that promise. With a duplicate, SwiftUI may show the wrong row's data, drop a row, animate the wrong row on delete, or log a warning about duplicate IDs, and the effect can differ between runs and iOS versions. Choose an id that is unique by construction (a UUID or a database key), not one that is unique only in today's data.
Delete, move and swipe actions
onDelete and onMove are modifiers on ForEach, not on List. SwiftUI hands you the row positions; you change the array, and the List updates.
offsets and source are IndexSets: several rows can be deleted or moved at once.struct ShoppingView: View {
@State private var items = ["Milk", "Bread", "Eggs", "Rice"]
var body: some View {
NavigationStack {
List {
ForEach(items, id: \.self) { item in
Text(item)
}
.onDelete { offsets in
items.remove(atOffsets: offsets) // swipe left, or edit mode
}
.onMove { source, destination in
items.move(fromOffsets: source, toOffset: destination)
}
}
.navigationTitle("Shopping")
.toolbar { EditButton() } // toggles edit mode
}
}
}onDeletealone gives swipe-to-delete. WithEditButton, edit mode also shows red delete buttons.onMoveshows drag handles in edit mode.remove(atOffsets:)andmove(fromOffsets:toOffset:)are array helpers that come with SwiftUI.
In plain Swift (no IndexSet), deleting several positions has one classic bug: removing from the front shifts every later index. Remove from the highest index down:
func removeWrong(_ items: [String], at offsets: [Int]) -> [String] {
var result = items
for i in offsets.sorted() { result.remove(at: i) } // ascending: indexes shift
return result
}
func remove(_ items: [String], at offsets: [Int]) -> [String] {
var result = items
for i in offsets.sorted(by: >) { result.remove(at: i) } // descending: safe
return result
}
let list = ["A", "B", "C", "D"]
print(removeWrong(list, at: [1, 2]))
print(remove(list, at: [1, 2]))Output
["A", "C"]
["A", "D"]toOffset in onMove is the position in the original array that the moved rows go in front of. Moving the first row to the end gives toOffset = count, not count - 1. This model behaves the same way:
func move(_ items: [String], from offsets: [Int], to destination: Int) -> [String] {
let moving = offsets.sorted().map { items[$0] }
var rest: [String] = []
for (i, item) in items.enumerated() where !offsets.contains(i) {
rest.append(item)
}
let insertAt = destination - offsets.filter { $0 < destination }.count
for (k, item) in moving.enumerated() {
rest.insert(item, at: insertAt + k)
}
return rest
}
let list = ["A", "B", "C", "D"]
print(move(list, from: [0], to: 2))
print(move(list, from: [0], to: 4))
print(move(list, from: [3], to: 0))Output
["B", "A", "C", "D"]
["B", "C", "D", "A"]
["D", "A", "B", "C"]Swipe actions
.tint colours a button.ForEach(tasks) { task in
Text(task.title)
.swipeActions(edge: .trailing, allowsFullSwipe: true) {
Button(role: .destructive) {
delete(task)
} label: {
Label("Delete", systemImage: "trash")
}
Button {
pin(task)
} label: {
Label("Pin", systemImage: "pin")
}
.tint(.orange)
}
.swipeActions(edge: .leading) {
Button("Done") { complete(task) }
.tint(.green)
}
}struct Chore {
var title: String
var done = false
}
var tasks = [Chore(title: "Read"), Chore(title: "Code")]
for var task in tasks {
task.done = true
}
print(tasks.map { $0.done })Show the answer
[false, false]Structs are copied: task is a copy, so the array never changes. Change the array element itself, found by its id. (In SwiftUI, ForEach($tasks) { $task in Toggle(task.title, isOn: $task.done) } gives each row a binding to the real element.)
struct Chore {
let id: Int
var title: String
var done = false
}
var tasks = [Chore(id: 1, title: "Read"), Chore(id: 2, title: "Code")]
func toggle(id: Int) {
if let i = tasks.firstIndex(where: { $0.id == id }) {
tasks[i].done.toggle()
}
}
toggle(id: 2)
print(tasks.map { $0.done })Output
[false, true]Search and refresh
.searchable(text:) adds a search field (in the navigation bar when inside a NavigationStack). It only gives you the text. You filter the data, usually with a computed property.
struct StudentListView: View {
let names = ["Asha", "Ravi", "Meera", "Kabir", "Ananya"]
@State private var query = ""
private var results: [String] {
if query.isEmpty { return names }
return names.filter { $0.localizedCaseInsensitiveContains(query) }
}
var body: some View {
NavigationStack {
List(results, id: \.self) { name in
Text(name)
}
.navigationTitle("Students")
.searchable(text: $query, prompt: "Search names")
.overlay {
if results.isEmpty {
ContentUnavailableView.search(text: query) // iOS 17
}
}
}
}
}func filtered(_ items: [String], by query: String) -> [String] {
if query.isEmpty { return items }
let q = query.lowercased()
return items.filter { $0.lowercased().contains(q) }
}
let fruits = ["Apple", "Mango", "Banana", "Grapes"]
print(filtered(fruits, by: ""))
print(filtered(fruits, by: "AN"))
print(filtered(fruits, by: "z"))Output
["Apple", "Mango", "Banana", "Grapes"]
["Mango", "Banana"]
[].refreshable { await store.reload() } adds pull-to-refresh. SwiftUI shows the spinner until the async closure finishes.
DisclosureGroup, OutlineGroup and tree data
DisclosureGroup shows a label with an arrow that expands or collapses its content. Pass isExpanded: a binding to control it from code.
struct AdvancedSettings: View {
@State private var showAdvanced = false
@State private var debugMode = false
@State private var betaFeatures = false
var body: some View {
Form {
DisclosureGroup("Advanced", isExpanded: $showAdvanced) {
Toggle("Debug mode", isOn: $debugMode)
Toggle("Beta features", isOn: $betaFeatures)
}
Button(showAdvanced ? "Collapse" : "Expand") {
withAnimation { showAdvanced.toggle() }
}
}
}
}Tree data (folders inside folders) needs a type that contains an optional array of itself. OutlineGroup and List(_:children:) walk it for you and nest DisclosureGroups as deep as the data goes.
children key path must point to an optional array of the same type.struct FileItem: Identifiable {
let id = UUID()
let name: String
var children: [FileItem]? = nil // nil = file, [] = empty folder
}
// 1. A List that shows the whole tree
List(items, children: \.children) { item in
Label(item.name, systemImage: item.children == nil ? "doc" : "folder")
}
// 2. OutlineGroup inside a List, so it can sit in a Section
List {
Section("My files") {
OutlineGroup(items, children: \.children) { item in
Text(item.name)
}
}
}Tree code is recursive: a function calls itself for each child. That is how OutlineGroup works, and how you count or measure a tree:
struct Node {
let name: String
var children: [Node]? = nil
}
let root = Node(name: "Documents", children: [
Node(name: "Swift", children: [
Node(name: "Lab1.swift"),
Node(name: "Lab2.swift"),
]),
Node(name: "Empty", children: []),
Node(name: "Resume.pdf"),
])
func depth(_ node: Node) -> Int {
1 + (node.children ?? []).map { depth($0) }.reduce(0) { max($0, $1) }
}
func fileCount(_ node: Node) -> Int {
guard let children = node.children else { return 1 } // a file
return children.map { fileCount($0) }.reduce(0, +)
}
func show(_ node: Node, level: Int = 0) {
let mark = node.children == nil ? "-" : "+"
print(String(repeating: " ", count: level) + mark + " " + node.name)
for child in node.children ?? [] {
show(child, level: level + 1)
}
}
show(root)
print("depth:", depth(root), "files:", fileCount(root))Output
+ Documents
+ Swift
- Lab1.swift
- Lab2.swift
+ Empty
- Resume.pdf
depth: 3 files: 3One expansion state per row
A list of DisclosureGroups, one per row, needs one open/closed flag per row. A single @State Bool shared by every row means every row reads and writes the same value.
struct Topic: Identifiable {
let id: Int
let title: String
let notes: [String]
}
struct TopicList: View {
let topics: [Topic]
@State private var isExpanded = false // ONE flag for ALL rows
var body: some View {
List(topics) { topic in
DisclosureGroup(topic.title, isExpanded: $isExpanded) {
ForEach(topic.notes, id: \.self) { Text($0) }
}
}
}
}Show the answer
They all open too. Every DisclosureGroup is bound to the same isExpanded, so tapping one sets the shared Bool to true and every row redraws expanded. Tapping any row again closes all of them.
Fix: store which rows are open. A Set of ids allows any number of open rows. Each row gets its own Binding built with Binding(get:set:): the getter asks whether this row's id is in the set, the setter inserts or removes it.
struct TopicList: View {
let topics: [Topic]
@State private var openIDs: Set<Topic.ID> = []
var body: some View {
List(topics) { topic in
DisclosureGroup(topic.title, isExpanded: isOpen(topic.id)) {
ForEach(topic.notes, id: \.self) { Text($0) }
}
}
}
// A Binding<Bool> for one row, backed by the shared Set
private func isOpen(_ id: Topic.ID) -> Binding<Bool> {
Binding(
get: { openIDs.contains(id) },
set: { open in
if open { openIDs.insert(id) } else { openIDs.remove(id) }
}
)
}
}Accordion (only one open at a time): store a single optional id. Opening a row replaces the id, which closes whichever row was open before. nil means all closed.
struct TopicAccordion: View {
let topics: [Topic]
@State private var openID: Topic.ID? = nil
var body: some View {
List(topics) { topic in
DisclosureGroup(
topic.title,
isExpanded: Binding(
get: { openID == topic.id },
set: { open in openID = open ? topic.id : nil }
)
) {
ForEach(topic.notes, id: \.self) { Text($0) }
}
}
}
}The logic behind both bindings is plain Swift, so you can test it in the Playground:
var openIDs: Set<Int> = []
func setOpen(_ id: Int, _ open: Bool) {
if open { openIDs.insert(id) } else { openIDs.remove(id) }
}
setOpen(2, true)
setOpen(3, true)
setOpen(2, false)
print("set:", openIDs.sorted())
var openID: Int? = nil
func setAccordion(_ id: Int, _ open: Bool) {
openID = open ? id : nil
}
setAccordion(2, true)
setAccordion(3, true) // opening 3 closes 2
print("accordion:", openID ?? -1, openID == 2)Output
set: [3]
accordion: 3 falseTry “DisclosureGroup, OutlineGroup and tree data” with live code →
Observation: @Observable, @State, @Bindable
@State is perfect for small values owned by one view. When several screens share the same data (a task list, a cart, a user profile), put it in a model class and share that one object. Classes are reference types: every view holding it sees the same instance.
final class Counter {
var value = 0
}
let owner = Counter()
let child = owner // same object, two references
child.value += 5
print(owner.value, owner === child)
struct CounterValue {
var value = 0
}
let a = CounterValue()
var b = a // a copy
b.value += 5
print(a.value, b.value)Output
5 true
0 5iOS 17's Observation framework makes a class observable with one macro: @Observable. SwiftUI then tracks which properties each body reads and redraws only the views that read a property that changed.
import SwiftUI
@Observable
final class Profile {
var name = "Asha"
var score = 0
@ObservationIgnored var cache: [String] = [] // not tracked
}
struct ProfileScreen: View {
@State private var profile = Profile() // this view creates and owns it
var body: some View {
VStack(spacing: 16) {
ScoreCard(profile: profile) // pass it as a plain property
NameEditor(profile: profile)
}
.padding()
}
}
struct ScoreCard: View {
let profile: Profile // no wrapper needed to read or call methods
var body: some View {
VStack {
Text("\(profile.name): \(profile.score)")
Button("Add point") { profile.score += 1 } // fine: it's a class
}
}
}
struct NameEditor: View {
@Bindable var profile: Profile // needed only for $ bindings
var body: some View {
TextField("Name", text: $profile.name)
}
}@Observableworks on classes only. All stored properties are tracked unless marked@ObservationIgnored.- The view that creates the model stores it in
@State, so it is created once and survives redraws. - Child views take it as a plain
letorvar. Readingprofile.scoreinbodyis enough for SwiftUI to watch it. @Bindablegives$profile.name, aBinding<String>for a TextField or Toggle. Without it,$profiledoesn't exist.
struct Profile {
var name = "Asha"
}
let profile = Profile()
profile.name = "Ravi"A struct held in a let can't change. A class instance can, even through a let, because let only fixes which object the name refers to. That is why ScoreCard can write profile.score += 1 with a plain let.
@ObservationIgnored
Every stored property of an @Observable class is tracked. Mark a property @ObservationIgnored when changing it should never redraw a view: a cache, a formatter, a counter used only for logging, a reference to a service. Views can still read it; they just aren't told when it changes.
@Observable
final class Inbox {
var messages: [String] = [] // tracked: drives the list
var unreadCount = 0 // tracked: drives a badge
@ObservationIgnored var fetchCount = 0 // bookkeeping only
@ObservationIgnored private var lastError: String?
func refresh() {
fetchCount += 1 // no view redraws for this
messages.append("Message \(fetchCount)") // this one redraws the list
}
}Text("Fetched \(inbox.fetchCount) times"). Tapping a button calls inbox.fetchCount += 1 and nothing else. Does the number on screen change?Show the answer
No. fetchCount is @ObservationIgnored, so the write isn't reported and the Text keeps the old number. It only catches up when the view redraws for some other reason, such as a change to a tracked property it also reads. That stale-UI effect is exactly why you ignore only properties no view should display.
Wrappers that don't mix
@Observable
final class Inbox { var messages: [String] = [] }
struct InboxScreen: View {
@StateObject private var inbox = Inbox() // error
var body: some View { Text("\(inbox.messages.count)") }
}@StateObject, @ObservedObject and @EnvironmentObject belong to the old ObservableObject world. An @Observable class doesn't conform to ObservableObject, so the compiler rejects them. Use @State to own it, a plain property to pass it, and @Environment(Inbox.self) to read it from the environment.
@Bindable is only for $. A child that reads inbox.messages or calls inbox.refresh() needs no wrapper at all: Observation tracks the read anyway. Add @Bindable only when you write $inbox.something to hand a Binding to a TextField, Toggle, Stepper or Picker. Adding it everywhere "just in case" works but tells the reader the view edits the model when it doesn't.
Try “Observation: @Observable, @State, @Bindable” with live code →
Seeing what redraws: _printChanges and tracking
"Which views redraw when this property changes?" is a favourite viva question. You can watch the answer yourself with a debugging helper SwiftUI ships: Self._printChanges(). Call it inside body; each time body runs, it prints the view's name and what caused the redraw.
@Observable
final class Match {
var homeGoals = 0
var awayGoals = 0
}
struct MatchScreen: View {
@State private var match = Match()
var body: some View {
let _ = Self._printChanges() // debug only: remove before shipping
VStack(spacing: 12) {
HomeLabel(match: match)
AwayLabel(match: match)
Button("Home scores") { match.homeGoals += 1 }
}
}
}
struct HomeLabel: View {
let match: Match
var body: some View {
let _ = Self._printChanges()
Text("Home \(match.homeGoals)") // reads homeGoals only
}
}
struct AwayLabel: View {
let match: Match
var body: some View {
let _ = Self._printChanges()
Text("Away \(match.awayGoals)") // reads awayGoals only
}
}- The leading underscore marks it as not public API: it is meant for debugging, may change, and shouldn't stay in shipped code.
- The output format isn't documented or guaranteed. Typical lines look like
MatchScreen: @self changed.or mention@dependencies,@identityor a property name, but don't write exam answers or code that depend on the exact text. - It prints to Xcode's console when
bodyruns, so it works in the Simulator and on a device, not in a static preview screenshot.
@Observable Match above, the user taps Home scores once. Which of the three bodies run again?Show the answer
Only HomeLabel. It is the only body that read homeGoals. AwayLabel read only awayGoals, and MatchScreen's body read neither property (it only passed the object along and wrote homeGoals inside a button action, and writes in actions aren't tracked reads). So only one line is printed.
final class OldMatch: ObservableObject {
@Published var homeGoals = 0
@Published var awayGoals = 0
}
struct OldHomeLabel: View {
@ObservedObject var match: OldMatch
var body: some View {
let _ = Self._printChanges()
Text("Home \(match.homeGoals)")
}
}
struct OldAwayLabel: View {
@ObservedObject var match: OldMatch
var body: some View {
let _ = Self._printChanges()
Text("Away \(match.awayGoals)")
}
}OldMatch (ObservableObject). Which label bodies run again?Show the answer
Both OldHomeLabel and OldAwayLabel. Any @Published change fires the object's single objectWillChange publisher, and every view observing the object is invalidated, whether or not it reads homeGoals. The parent that owns it with @StateObject is invalidated too. Observation tracks per property per body; ObservableObject notifies per object.
@Observable version. You add Text("Total \(match.homeGoals + match.awayGoals)") to MatchScreen's body. Now which bodies run when Home scores?Show the answer
MatchScreen and HomeLabel. MatchScreen's body now reads both properties, so it depends on homeGoals. When a parent body re-runs, SwiftUI builds new HomeLabel and AwayLabel values, but it only re-runs a child's body if the child's inputs or tracked properties changed. AwayLabel's input is the same object and awayGoals didn't change, so typically it isn't re-run. Check with _printChanges rather than trusting a rule of thumb.
Try “Seeing what redraws: _printChanges and tracking” with live code →
@Environment
Passing a model through five layers of views gets tedious. The environment is a set of values SwiftUI passes down the view tree automatically. Put a model in with .environment(model); read it anywhere below with @Environment(Model.self).
@main
struct ScoresApp: App {
@State private var profile = Profile()
var body: some Scene {
WindowGroup {
ContentView()
.environment(profile) // available to every view inside
}
}
}
struct BadgeView: View {
@Environment(Profile.self) private var profile
var body: some View {
@Bindable var profile = profile // local @Bindable for $ bindings (iOS 17)
VStack {
Text("Score: \(profile.score)")
TextField("Name", text: $profile.name)
}
}
}
#Preview {
BadgeView()
.environment(Profile()) // previews need it too
}Optional environment objects
struct SyncBadge: View {
@Environment(Profile.self) private var profile: Profile? // optional: nil if not injected
var body: some View {
if let profile {
Text("Signed in as \(profile.name)")
} else {
Text("Not signed in")
}
}
}
#Preview("No profile") {
SyncBadge() // fine: shows "Not signed in" instead of crashing
}| Declaration | Not injected | Use when |
|---|---|---|
@Environment(Profile.self) private var profile | Runtime crash on first read | The app always injects it; a crash finds the missing .environment early |
@Environment(Profile.self) private var profile: Profile? | nil | The view also works without it: reusable components, previews, optional features |
Built-in environment values
struct DetailView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@Environment(\.horizontalSizeClass) private var sizeClass
var body: some View {
VStack {
Text(colorScheme == .dark ? "Dark mode" : "Light mode")
if sizeClass == .compact {
Text("iPhone portrait layout")
} else {
Text("Wide layout")
}
Button("Close") { dismiss() } // closes a sheet or pops a pushed view
}
}
}
#Preview {
DetailView()
.environment(\.colorScheme, .dark) // override a value for a subtree
}| Key path | Type | Use |
|---|---|---|
\.dismiss | DismissAction | Call dismiss() to close a sheet or go back |
\.colorScheme | ColorScheme (.light, .dark) | Adapt colours or images |
\.horizontalSizeClass | UserInterfaceSizeClass? (.compact, .regular) | Choose a layout for narrow or wide screens |
\.editMode | Binding<EditMode>? | Know whether the List is in edit mode |
\.locale | Locale | Format text for the user's region |
ObservableObject: the older API
Before iOS 17, models used the Combine-based ObservableObject protocol. Most existing apps, tutorials and exam papers still use it, so learn both.
final class ScoreStore: ObservableObject {
@Published var score = 0 // each @Published change notifies observers
@Published var name = "Asha"
}
struct OldRoot: View {
@StateObject private var store = ScoreStore() // creates and owns it
var body: some View {
VStack {
OldScoreView(store: store)
OldBadge()
}
.environmentObject(store)
}
}
struct OldScoreView: View {
@ObservedObject var store: ScoreStore // passed in, not owned
var body: some View {
TextField("Name", text: $store.name) // bindings come built in
}
}
struct OldBadge: View {
@EnvironmentObject var store: ScoreStore // read from the environment
var body: some View {
Text("Score: \(store.score)")
}
}| Job | Before iOS 17 (ObservableObject) | iOS 17+ (Observation) |
|---|---|---|
| Make a class observable | Conform to ObservableObject; mark each property @Published | Add the @Observable macro; every stored property is tracked |
| Create and own it in a view | @StateObject | @State |
| Pass it to a child | @ObservedObject var store | Plain let store / var store |
Get $ bindings in a child | @ObservedObject already gives them | @Bindable var store |
| Share through the hierarchy | .environmentObject(store) + @EnvironmentObject | .environment(store) + @Environment(Store.self) |
| What redraws a view | Any @Published change, even ones the view doesn't show | Only properties the view's body read |
| Missing from environment | Runtime crash | Runtime crash (unless declared optional) |
| Needs | Combine | Observation (iOS 17) |
Which wrapper when?
| Situation | Use |
|---|---|
| A simple value only this view changes (text, toggle, selection) | @State private var |
| A child must change a value its parent owns | @Binding |
This view creates an @Observable model | @State private var model = Model() |
| A child only reads the model or calls its methods | Plain let model: Model |
A child needs $model.property for a control | @Bindable var model: Model |
| Many distant views need the same model | .environment(model) + @Environment(Model.self) |
| A system value: dismiss, colour scheme, size class | @Environment(\.key) |
| A preference that survives relaunch | @AppStorage |
Bug hunt: Observation
A small shop screen with five planted mistakes, each marked with a letter. For each one, write down what goes wrong (compile error, crash or wrong behaviour) and the fix, then reveal the key.
import SwiftUI
@Observable
final class Basket {
var items: [String] = []
var note = ""
}
struct ShopRoot: View {
@StateObject private var basket = Basket() // [A]
var body: some View {
NavigationStack {
ShelfView(basket: basket)
} // [B]
}
}
struct ShelfView: View {
let basket: Basket
let products = ["Pen", "Notebook", "Pen"]
var body: some View {
List {
TextField("Gift note", text: $basket.note) // [C]
ForEach(products, id: \.self) { product in // [D]
Button("Add \(product)") { basket.items.append(product) }
}
BasketSummary()
}
.toolbar { BasketBadge() }
}
}
struct BasketBadge: View {
@Environment(Basket.self) private var basket
var body: some View { Text("\(basket.items.count)") }
}
struct BasketSummary: View {
@State private var basket = Basket() // [E]
var body: some View { Text("Items: \(basket.items.count)") }
}Show the bugs
- [A] Compile error:
@StateObjectneeds anObservableObject;Basketis@Observable. Fix:@State private var basket = Basket(). - [B] Nothing calls
.environment(basket), soBasketBadge's@Environment(Basket.self)crashes at runtime when it is first read. Fix: Add.environment(basket)to theNavigationStack(or any ancestor of the badge). - [C] Compile error:
$basketdoesn't exist on a plainletholding an@Observableobject. Fix: Declare@Bindable var basket: Basket, or create a local@Bindable var basket = basketinsidebody. - [D] "Pen" appears twice, so
id: \.selfgives two rows the same identity: wrong or missing rows and a duplicate-ID warning. Fix: Use anIdentifiableproduct struct with a unique id, or make the data unique. - [E]
BasketSummarycreates its own second Basket, which is always empty: it never sees items added to the shared one. Fix: Don't create it here: read@Environment(Basket.self)or takelet basket: Basketfrom the parent.
Exam traps
| Code or claim | What really happens |
|---|---|
List(names, id: \.self) with duplicate names | Two rows share an identity: wrong rows or odd animations |
List(items) { } where items isn't Identifiable | Compile error: add Identifiable or id: |
.onDelete on a List | Compile error: it's a ForEach modifier |
onMove destination for first row → end | toOffset is count, not count - 1 |
| Deleting several indexes in ascending order | Later indexes shift: delete from the highest down |
Row has .swipeActions | Automatic onDelete swipe disappears; add your own delete button |
for var task in tasks { task.done = true } | Changes copies; the array is unchanged |
.searchable(text:) | Gives you text only; you filter the data |
| onDelete offsets while searching | Refer to the filtered array, not the full one |
children: [Node] (not optional) in OutlineGroup | Compile error: needs [Node]? |
children: [] vs nil | Empty folder with an arrow vs leaf with no arrow |
@Observable struct Model | Compile error: @Observable is for classes |
Owner declares let model = Model() | New model each time the view is recreated; use @State |
$model.name with a plain let model | Compile error: use @Bindable |
@Environment(Model.self) without .environment(model) | Runtime crash (also in previews) |
@ObservedObject var store = Store() | Recreated on parent redraw: use @StateObject |
ObservableObject property without @Published | Changes don't update the UI |
@Environment(\.dismiss) vs @Environment(Model.self) | Key path for system values vs type for your model |
@StateObject / @ObservedObject / @EnvironmentObject in iOS 17 | @State / plain property (or @Bindable) / @Environment(Type.self) |
List(clubs, id: .name) where two clubs share a name | Compiles, then shows wrong or missing rows: pick an id unique by construction |
One @State var isExpanded for every DisclosureGroup row | Every row opens and closes together: use Set<ID> or ID? with Binding(get:set:) |
@StateObject private var m = ObservableModel() where the type is @Observable | Compile error: needs ObservableObject; use @State |
A displayed property marked @ObservationIgnored | Screen doesn't update when it changes |
Self._printChanges() | Debug-only, underscored API; output text isn't guaranteed |
Viva questions and answers
Why must List data be Identifiable?
SwiftUI needs a stable identity for each row to know which rows were inserted, removed or moved, and to keep row state attached to the right data. Identifiable provides it through the id property; id: supplies a key path instead.
List vs ForEach?
List is a scrolling container with system styling. ForEach is a view that creates one view per element and has no look of its own. You put ForEach inside a List to mix static rows, sections and editing modifiers.
How do you delete and reorder rows?
Attach onDelete and onMove to the ForEach and update the array with remove(atOffsets:) and move(fromOffsets:toOffset:). An EditButton turns on edit mode for delete buttons and drag handles.
How does search work in SwiftUI?
.searchable(text:) binds a search field to a String. You filter the data yourself, usually in a computed property, and show that filtered array in the List.
What is OutlineGroup?
A view that walks tree data through a children key path to an optional array, and shows each level as an expandable disclosure group. List(_:children:) does the same for a whole List.
Why are the children optional?
nil marks a leaf, which gets no disclosure arrow. An empty array is a node that can have children but currently has none, like an empty folder.
What does the @Observable macro do?
It turns a class into an observable type: it generates code that records which properties each view reads and notifies only those views when the properties change. It is part of the Observation framework, iOS 17.
Where do you store an @Observable model?
In @State in the view or App that creates it, so it's created once and kept across redraws. Other views receive it as a plain property or through the environment.
When do you need @Bindable?
When a view needs bindings to an @Observable model's properties, for example $model.name for a TextField. Reading properties or calling methods doesn't need it.
@Environment with a key path vs a type?
A key path like \.dismiss or \.colorScheme reads a value the system provides. A type like Store.self reads an @Observable object you injected with .environment(store).
@StateObject vs @ObservedObject?
@StateObject creates and owns an ObservableObject and keeps it alive across redraws. @ObservedObject only watches an object passed in from outside; if you create one there, it's recreated each time the parent redraws.
What is the iOS 17 equivalent of each older wrapper?
ObservableObject + @Published becomes @Observable; @StateObject becomes @State; @ObservedObject becomes a plain property, or @Bindable for bindings; @EnvironmentObject becomes @Environment(Type.self).
Why is @Observable more efficient than ObservableObject?
ObservableObject publishes one change signal for the whole object, so every observing view redraws. @Observable tracks individual properties, so only views that read the changed property redraw.
Why must a shared model be a class?
Several views must see and change the same instance. A struct would be copied into each view, so changes in one wouldn't appear in the others.
How do you close a sheet from inside it?
Read @Environment(\.dismiss) private var dismiss and call dismiss(). It also pops a view pushed onto a NavigationStack.
How do you choose between @State, @Binding, @Bindable and @Environment?
@State for data this view owns, including the model it creates. @Binding for a value type owned by a parent. @Bindable for bindings into an @Observable object you were given. @Environment when many distant views need the same object or a system value.
How would you show which views redraw when a property changes?
Add let _ = Self._printChanges() at the top of each body and watch the console. It's an underscored debugging helper: fine while investigating, but its output format isn't guaranteed and it shouldn't ship.
Why does one @State var isExpanded open every DisclosureGroup in a list?
Every row's isExpanded: binding points at the same Bool, so they all read and write one value. Store per-row state instead, such as a Set of open ids, and give each row its own Binding(get:set:) that checks and updates its id.
What does @ObservationIgnored do and when would you use it?
It removes one stored property of an @Observable class from tracking, so changing it never redraws a view. Use it for caches, counters and services that no view displays.
What changes when you migrate from ObservableObject to @Observable?
Remove the protocol and every @Published, add the macro; @StateObject becomes @State; @ObservedObject becomes a plain property, or @Bindable where $ is needed; .environmentObject and @EnvironmentObject become .environment and @Environment(Type.self). Redraws become per property instead of per object.
Quiz
What must elements conform to for
List(items) { ... }without anid:argument?Show the answer
Identifiable
When is
id: \.selfa bad choice?Show the answer
When values can repeat or change
The id must be unique and stable; duplicates confuse SwiftUI's row identity.
Which view do you attach
onDeleteto?Show the answer
ForEach
What does
EditButton()do?Show the answer
Toggles the list's edit mode
Rows are
[A, B, C, D]. The user drags A to the very end. WhattoOffsetdoesonMovereceive?Show the answer
4
The offset is the position in the original array to insert before; the end is
count.What does this print?
Show the answer
["A", "C"]
After removing index 1, C moves to index 1 and D to index 2, so D is removed next.
What does
.searchable(text: $query)do by itself?Show the answer
Adds a search field bound to
queryWhat type must the
childrenkey path point to forOutlineGroup?Show the answer
[Item]?In tree data, what does
children: []mean compared withchildren: nil?Show the answer
[]is an empty folder;nilis a leafWhich parameter lets code open or close a DisclosureGroup?
Show the answer
isExpanded:In iOS 17, how should the view that creates an
@Observablemodel store it?Show the answer
@State private var model = Model()A child view needs
TextField("Name", text: $model.name). How should it declaremodel?Show the answer
@Bindable var model: ModelHow does a view read an
@Observablemodel put in the environment with.environment(store)?Show the answer
@Environment(Store.self) private var storeWhat happens if no ancestor provides the model for
@Environment(Store.self)?Show the answer
Runtime crash
Which redraws fewer views when one property changes?
Show the answer
@Observable
Observation tracks which properties each body read; ObservableObject notifies on any @Published change.
What is the iOS 17 replacement for
@EnvironmentObject?Show the answer
@Environment(Type.self)Why is
@ObservedObject var store = Store()a bug?Show the answer
The store is recreated whenever the parent redraws
What does
@Environment(\.dismiss) private var dismissgive you?Show the answer
An action you call to close the current sheet or pushed view
Which can
@Observablebe applied to?Show the answer
A class
Every row of a List has
DisclosureGroup(t.title, isExpanded: $isExpanded)with one@State var isExpanded. The user opens one row. What happens?Show the answer
Every row opens
All rows share one Bool. Store a
Setof open ids (or one optional id for an accordion) and build aBindingper row.An accordion shows at most one open row. Which state fits best?
Show the answer
@State var openID: Topic.ID? = nilA single optional id can only name one row; opening another replaces it.
With
@Observable, a parent passes the model toHomeLabel(readshomeGoals) andAwayLabel(readsawayGoals).homeGoalschanges. Which label bodies re-run?Show the answer
Only HomeLabel
Observation records which properties each body read. With ObservableObject both would be invalidated.
What does
@StateObject private var store = Store()do whenStoreis@Observable(not ObservableObject)?Show the answer
Compile error
Which declaration returns
nilinstead of crashing when no ancestor injected the model?Show the answer
@Environment(Store.self) var store: Store?
← State, bindings, controls and forms · Navigation and presentation →
Practise this lesson interactively →