ViewLab

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

Contents

  1. List basics
  2. Delete, move and swipe actions
  3. Search and refresh
  4. DisclosureGroup, OutlineGroup and tree data
  5. Observation: @Observable, @State, @Bindable
  6. Seeing what redraws: _printChanges and tracking
  7. @Environment
  8. ObservableObject: the older API
  9. 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).

Dynamic rows need a stable, unique identity for each element.
// 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 id

Output

[1, 2, 3]
3 2

Sections, ForEach and list styles

Use 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 styleLooks like
.automaticThe default: the system picks a style for the context
.plainEdge-to-edge rows, no grouped background
.groupedGrey background, sections as full-width blocks
.insetGroupedRounded section cards with margins: the Settings look
.insetPlain rows with side margins
.sidebarCollapsible sections, for a sidebar in a split view
List(items) { }ForEach(items) { }
What it isA scrolling container with rowsA view builder that repeats content; no scrolling or style
Mix static and dynamic rowsNo (use List { ForEach })Yes, inside a List, VStack or Section
onDelete / onMoveNot availableAvailable

Trap: an id key path that isn't unique

Compiles fine. The bug only shows when names repeat.
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.

Try “List basics” with live code →

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
        }
    }
}

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

The first button is the full-swipe action. .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)
        }
}
What does this print?
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]

Try “Delete, move and swipe actions” with live code →

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.

The 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: 3

One 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.

Bug: tapping any row opens (or closes) every row.
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) }
            }
        }
    }
}
The user taps the arrow on the second topic only. What happens to the other rows?
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.

Many rows open at once: Set<ID> plus a custom Binding.
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.

One open row: ID? plus a custom Binding.
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 false

Try “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 5

iOS 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.

Own with @State, pass as a plain property, use @Bindable when a control needs a binding.
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)
    }
}
This doesn't compile
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
    }
}
A view shows 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

Compile error: @StateObject requires a type that conforms to ObservableObject.
@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.

let _ = ... is how you run a statement inside a view builder.
@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
    }
}
With the @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.

The same experiment with ObservableObject.
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)")
    }
}
Same tap, but with 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.

Back to the @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).

Reading a model that was never put in the environment crashes at runtime.
@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

Declaring the property type as Profile? selects the optional form of @Environment(Type.self).
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
}
DeclarationNot injectedUse when
@Environment(Profile.self) private var profileRuntime crash on first readThe app always injects it; a crash finds the missing .environment early
@Environment(Profile.self) private var profile: Profile?nilThe 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 pathTypeUse
\.dismissDismissActionCall dismiss() to close a sheet or go back
\.colorSchemeColorScheme (.light, .dark)Adapt colours or images
\.horizontalSizeClassUserInterfaceSizeClass? (.compact, .regular)Choose a layout for narrow or wide screens
\.editModeBinding<EditMode>?Know whether the List is in edit mode
\.localeLocaleFormat text for the user's region

Try “@Environment” with live code →

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.

The same app in the pre-iOS 17 style.
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)")
    }
}
JobBefore iOS 17 (ObservableObject)iOS 17+ (Observation)
Make a class observableConform to ObservableObject; mark each property @PublishedAdd the @Observable macro; every stored property is tracked
Create and own it in a view@StateObject@State
Pass it to a child@ObservedObject var storePlain 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 viewAny @Published change, even ones the view doesn't showOnly properties the view's body read
Missing from environmentRuntime crashRuntime crash (unless declared optional)
NeedsCombineObservation (iOS 17)

Which wrapper when?

SituationUse
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 methodsPlain 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

Try “ObservableObject: the older API” with live code →

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.

Five defects: two compile errors, one crash, two silent wrong-behaviour bugs.
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: @StateObject needs an ObservableObject; Basket is @Observable. Fix: @State private var basket = Basket().
  • [B] Nothing calls .environment(basket), so BasketBadge's @Environment(Basket.self) crashes at runtime when it is first read. Fix: Add .environment(basket) to the NavigationStack (or any ancestor of the badge).
  • [C] Compile error: $basket doesn't exist on a plain let holding an @Observable object. Fix: Declare @Bindable var basket: Basket, or create a local @Bindable var basket = basket inside body.
  • [D] "Pen" appears twice, so id: \.self gives two rows the same identity: wrong or missing rows and a duplicate-ID warning. Fix: Use an Identifiable product struct with a unique id, or make the data unique.
  • [E] BasketSummary creates 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 take let basket: Basket from the parent.

Try “Bug hunt: Observation” with live code →

Exam traps

Code or claimWhat really happens
List(names, id: \.self) with duplicate namesTwo rows share an identity: wrong rows or odd animations
List(items) { } where items isn't IdentifiableCompile error: add Identifiable or id:
.onDelete on a ListCompile error: it's a ForEach modifier
onMove destination for first row → endtoOffset is count, not count - 1
Deleting several indexes in ascending orderLater indexes shift: delete from the highest down
Row has .swipeActionsAutomatic 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 searchingRefer to the filtered array, not the full one
children: [Node] (not optional) in OutlineGroupCompile error: needs [Node]?
children: [] vs nilEmpty folder with an arrow vs leaf with no arrow
@Observable struct ModelCompile 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 modelCompile 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 @PublishedChanges 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 nameCompiles, then shows wrong or missing rows: pick an id unique by construction
One @State var isExpanded for every DisclosureGroup rowEvery row opens and closes together: use Set<ID> or ID? with Binding(get:set:)
@StateObject private var m = ObservableModel() where the type is @ObservableCompile error: needs ObservableObject; use @State
A displayed property marked @ObservationIgnoredScreen 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

  1. What must elements conform to for List(items) { ... } without an id: argument?

    Show the answer

    Identifiable

  2. When is id: \.self a bad choice?

    Show the answer

    When values can repeat or change

    The id must be unique and stable; duplicates confuse SwiftUI's row identity.

  3. Which view do you attach onDelete to?

    Show the answer

    ForEach

  4. What does EditButton() do?

    Show the answer

    Toggles the list's edit mode

  5. Rows are [A, B, C, D]. The user drags A to the very end. What toOffset does onMove receive?

    Show the answer

    4

    The offset is the position in the original array to insert before; the end is count.

  6. 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.

  7. What does .searchable(text: $query) do by itself?

    Show the answer

    Adds a search field bound to query

  8. What type must the children key path point to for OutlineGroup?

    Show the answer

    [Item]?

  9. In tree data, what does children: [] mean compared with children: nil?

    Show the answer

    [] is an empty folder; nil is a leaf

  10. Which parameter lets code open or close a DisclosureGroup?

    Show the answer

    isExpanded:

  11. In iOS 17, how should the view that creates an @Observable model store it?

    Show the answer

    @State private var model = Model()

  12. A child view needs TextField("Name", text: $model.name). How should it declare model?

    Show the answer

    @Bindable var model: Model

  13. How does a view read an @Observable model put in the environment with .environment(store)?

    Show the answer

    @Environment(Store.self) private var store

  14. What happens if no ancestor provides the model for @Environment(Store.self)?

    Show the answer

    Runtime crash

  15. 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.

  16. What is the iOS 17 replacement for @EnvironmentObject?

    Show the answer

    @Environment(Type.self)

  17. Why is @ObservedObject var store = Store() a bug?

    Show the answer

    The store is recreated whenever the parent redraws

  18. What does @Environment(\.dismiss) private var dismiss give you?

    Show the answer

    An action you call to close the current sheet or pushed view

  19. Which can @Observable be applied to?

    Show the answer

    A class

  20. 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 Set of open ids (or one optional id for an accordion) and build a Binding per row.

  21. An accordion shows at most one open row. Which state fits best?

    Show the answer

    @State var openID: Topic.ID? = nil

    A single optional id can only name one row; opening another replaces it.

  22. With @Observable, a parent passes the model to HomeLabel (reads homeGoals) and AwayLabel (reads awayGoals). homeGoals changes. Which label bodies re-run?

    Show the answer

    Only HomeLabel

    Observation records which properties each body read. With ObservableObject both would be invalidated.

  23. What does @StateObject private var store = Store() do when Store is @Observable (not ObservableObject)?

    Show the answer

    Compile error

  24. Which declaration returns nil instead 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 →