ViewLab

Swift & SwiftUI course › Session 7

Lifecycle, animation and persistence

When views appear and disappear, how SwiftUI animates changes, and how an app saves data: Codable and JSON, UserDefaults, files and SwiftData.

About 25 minutes · covers Lifecycle, animations, Codable, persistence, SwiftData

Open the interactive lesson (live previews, quizzes) →

What you'll learn

Contents

  1. View lifecycle
  2. App lifecycle and scenePhase
  3. Predict the console: lifecycle experiments
  4. Animations
  5. Transitions and matchedGeometryEffect
  6. Codable and JSON
  7. Choosing where to store data
  8. SwiftData
  9. Bug hunt: lifecycle

View lifecycle

A SwiftUI view struct is cheap and is re-created often, so you never put work in its init. Instead you attach lifecycle modifiers that run when the view appears on screen, disappears, or when a value changes.

onAppear, onDisappear and task on one view.
struct ProfileView: View {
    let userID: Int
    @State private var name = "Loading…"
    @State private var visits = 0

    var body: some View {
        Text(name)
            .onAppear { visits += 1 }                 // every time it comes on screen
            .onDisappear { print("left profile") }    // every time it goes off screen
            .task {                                   // async work tied to the view's life
                name = await loadName(for: userID)
            }
    }

    func loadName(for id: Int) async -> String {
        try? await Task.sleep(for: .seconds(1))       // stands in for a network call
        return "Student \(id)"
    }
}
ModifierRunsAsync?Cancelled automatically?
.onAppear { }Each time the view appearsNo (synchronous)Not applicable
.onDisappear { }Each time the view disappearsNoNot applicable
.task { }Before the view appearsYes: you can awaitYes, when the view disappears
.task(id: value) { }On appear, and again whenever value changesYesYes: the old task is cancelled before the new one starts
.onChange(of: value) { old, new in }When value changes (not on first appear unless initial: true)NoNot applicable

Why .task over onAppear + Task { }: a Task you create yourself keeps running after the user leaves the screen. .task is cancelled automatically when the view disappears, so a slow download stops instead of updating a screen nobody sees.

task(id:): restart when an input changes

Each keystroke changes query, which cancels the previous task. Only a pause of 300 ms lets a search finish.
struct SearchView: View {
    @State private var query = ""
    @State private var results: [String] = []

    var body: some View {
        List(results, id: \.self) { Text($0) }
            .searchable(text: $query)
            .task(id: query) {
                try? await Task.sleep(for: .milliseconds(300))   // debounce typing
                guard !Task.isCancelled else { return }
                results = await search(query)
            }
    }

    func search(_ text: String) async -> [String] {
        ["Swift", "SwiftUI", "SwiftData"].filter { text.isEmpty || $0.contains(text) }
    }
}

onChange(of:)

In iOS 17 the closure takes two parameters, the old and new values, or none. The one-parameter form { newValue in } from iOS 14 is deprecated. Add initial: true to also run it when the view first appears.

The iOS 17 forms of onChange.
.onChange(of: score) { oldValue, newValue in
    if newValue > oldValue { message = "Up by \(newValue - oldValue)" }
}
.onChange(of: score) {                 // zero-parameter form: read score directly
    saveScore()
}
.onChange(of: selectedTab, initial: true) { _, tab in
    print("showing", tab)
}

It works like a property observer in plain Swift: didSet also sees the old value (oldValue) and the new one.

What does this print?
struct Scoreboard {
    var score = 0 {
        didSet { print("changed", oldValue, "->", score) }
    }
}
var board = Scoreboard()
board.score = 5
board.score += 2
board.score = 7
Show the answer
changed 0 -> 5
changed 5 -> 7
changed 7 -> 7

Try “View lifecycle” with live code →

App lifecycle and scenePhase

The @main struct conforming to App is the entry point. Its init() runs once at launch, before any view; its body returns scenes, usually one WindowGroup. App-wide setup (a model container, shared models) lives here.

scenePhase read at the App level reports the state of the app as a whole.
@main
struct StudyApp: App {
    @Environment(\.scenePhase) private var scenePhase

    init() {
        print("App launched")            // once, at startup
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { _, phase in
            if phase == .background {
                print("save work here")
            }
        }
    }
}
ScenePhaseMeaningTypical reaction
.activeOn screen and receiving inputRefresh data, resume timers
.inactiveVisible but not interactive (app switcher, an incoming call banner, Control Centre)Pause games and timers
.backgroundNot visible; may be suspended soonSave data, stop work

ScenePhase is an ordinary enum, so the reaction is an ordinary switch. Plain-Swift model of the logic:

enum Phase {
    case active, inactive, background
}

func react(from old: Phase, to new: Phase) -> String {
    switch (old, new) {
    case (.background, .active), (.inactive, .active):
        return "resume timer"
    case (_, .inactive):
        return "pause timer"
    case (_, .background):
        return "save notes"
    default:
        return "nothing"
    }
}

let changes: [(Phase, Phase)] = [(.active, .inactive), (.inactive, .background),
                                 (.background, .active), (.active, .active)]
for (old, new) in changes {
    print(react(from: old, to: new))
}

Output

pause timer
save notes
resume timer
nothing

Switching over the real ScenePhase

ScenePhase comes from Apple's SDK, which may add cases later.
.onChange(of: scenePhase) { _, phase in
    switch phase {
    case .active: timer.resume()
    case .inactive: timer.pause()
    case .background: store.save()
    @unknown default: break        // a future SDK may add phases
    }
}

Your own enum Phase above is frozen from the compiler's point of view: you know every case. ScenePhase is declared in SwiftUI, a library that may add cases in a later iOS, so a switch over it that lists only the three known cases gets a compiler warning asking you to handle unknown values. @unknown default handles them and still warns you if a new SDK adds a case you haven't listed. A plain default: also compiles, but silently swallows new cases.

Try “App lifecycle and scenePhase” with live code →

Predict the console: lifecycle experiments

The Playground can't run SwiftUI, but you can still practise predicting. Each experiment below prints from lifecycle modifiers. Decide what the console shows, then reveal. Build them in Xcode afterwards and compare: where the answer says the order isn't guaranteed, believe the console, not a rule.

1. onAppear on rows

struct RowLog: View {
    let numbers = Array(1...200)

    var body: some View {
        List {
            ForEach(numbers, id: \.self) { n in
                Text("Row \(n)")
                    .onAppear { print("appear", n) }
                    .onDisappear { print("disappear", n) }
            }
        }
    }
}
The screen fits about 15 rows. What is printed at launch, and what happens when you scroll down?
Show the answer

onAppear is attached to each row, so it fires per row, not once for the list. List is lazy: at launch only the rows about to be visible (roughly the first screenful, sometimes a few extra) print appear. Scrolling prints appear for rows coming in and disappear for rows leaving; scroll back up and the early rows appear again. Inside a plain VStack (not lazy) all 200 would print appear at once. The exact rows and their order aren't documented, so don't build logic on them; this is why onAppear on the last row is a common but approximate "load more" trigger.

2. An if-toggled view

struct ToggleLog: View {
    @State private var showHint = false

    var body: some View {
        VStack {
            Button("Toggle hint") { showHint.toggle() }
            if showHint {
                Text("Swipe left to delete")
                    .onAppear { print("hint appear") }
                    .onDisappear { print("hint disappear") }
            }
            Text("Always here")
                .opacity(showHint ? 0.5 : 1)
                .onAppear { print("always appear") }
        }
    }
}
What prints at launch, then after tapping Toggle hint three times?
Show the answer

Launch: always appear only (the hint isn't in the hierarchy). Tap 1: hint appear. Tap 2: hint disappear. Tap 3: hint appear. always appear never prints again: changing opacity (even to 0) keeps the view in the hierarchy, so it doesn't disappear. An if inserts and removes the view, which is what lifecycle events follow.

3. Pushing and popping

struct PushLog: View {
    var body: some View {
        NavigationStack {
            NavigationLink("Open detail") {
                Text("Detail")
                    .onAppear { print("detail appear") }
                    .onDisappear { print("detail disappear") }
            }
            .onAppear { print("root appear") }
            .onDisappear { print("root disappear") }
        }
    }
}
Launch, tap Open detail, then tap Back. Which lines print?
Show the answer

Launch: root appear. Push: detail appear and root disappear. Back: detail disappear and root appear again. So onAppear on the root runs twice: once at launch and once on return, which is why one-time loading shouldn't live in a plain onAppear. The relative order within each step (does the new screen appear before the old one disappears?) depends on the iOS version and animation timing; it isn't guaranteed, so never write code that relies on it.

4. Presenting a sheet

struct SheetLog: View {
    @State private var showSheet = false

    var body: some View {
        Button("Show sheet") { showSheet = true }
            .onAppear { print("main appear") }
            .onDisappear { print("main disappear") }
            .sheet(isPresented: $showSheet) {
                Text("Sheet")
                    .onAppear { print("sheet appear") }
                    .onDisappear { print("sheet disappear") }
            }
    }
}
Launch, open the sheet, swipe it down. Which lines print?
Show the answer

Launch: main appear. Open: sheet appear. Dismiss: sheet disappear. main disappear does not print and main appear doesn't print again: a standard sheet covers the presenting view only partly, so SwiftUI keeps it on screen. Refresh work you'd normally do in the main view's onAppear after a sheet closes belongs in the sheet's onDismiss: closure or an onChange of the data. Full-screen covers can behave differently, so test them separately.

Try “Predict the console: lifecycle experiments” with live code →

Animations

SwiftUI animates state changes. You change a value; SwiftUI works out the old and new layouts and draws the frames in between. There are two ways to say "animate this change".

Implicit .animation(_:value:) on a view vs explicit withAnimation around a state change.
struct AnimationDemo: View {
    @State private var isBig = false
    @State private var angle = 0.0

    var body: some View {
        VStack(spacing: 40) {
            // 1. Implicit: this view animates whenever isBig changes
            Circle()
                .fill(isBig ? Color.orange : Color.blue)
                .frame(width: isBig ? 200 : 100, height: isBig ? 200 : 100)
                .animation(.spring, value: isBig)
                .onTapGesture { isBig.toggle() }

            // 2. Explicit: everything affected by this change animates
            Image(systemName: "arrow.up")
                .font(.largeTitle)
                .rotationEffect(.degrees(angle))
            Button("Rotate") {
                withAnimation(.easeInOut(duration: 0.6)) {
                    angle += 90
                }
            }
        }
    }
}
.animation(_:value:) (implicit)withAnimation { } (explicit)
Attached toA viewThe code that changes state
AnimatesChanges to that view (and its children) when value changesEvery view affected by the state changed inside the closure
Good forOne view that always animates the same wayA button action; insertions and removals; several views at once
Watch outNeeds value:; the old .animation(_:) without it is deprecatedOnly changes made inside the closure animate

Curves

What can animate? Anything SwiftUI can interpolate between two values: opacity, frame size, offset, scale, rotation, corner radius, colours and positions in a layout. An animation is just a series of in-between values over time:

func value(from start: Double, to end: Double, progress: Double) -> Double {
    start + (end - start) * progress       // linear interpolation
}
for progress in [0.0, 0.25, 0.5, 0.75, 1.0] {
    print(progress, value(from: 100, to: 200, progress: progress))
}

Output

0.0 100.0
0.25 125.0
0.5 150.0
0.75 175.0
1.0 200.0

A curve such as .easeInOut changes how progress moves over time; it still starts at the old value and ends at the new one. A Bool or an if that adds or removes a view can't be interpolated, so those changes use a transition instead.

Try “Animations” with live code →

Transitions and matchedGeometryEffect

A transition describes how a view enters or leaves when it is inserted or removed (for example by an if). The default is a fade (.opacity). A transition only plays when the insertion or removal happens inside an animation.

The banner slides in from the top and fades. Without withAnimation it just appears and disappears.
struct BannerDemo: View {
    @State private var showBanner = false

    var body: some View {
        VStack {
            Button("Toggle banner") {
                withAnimation(.snappy) {          // required: insertion/removal must be animated
                    showBanner.toggle()
                }
            }
            if showBanner {
                Text("Saved!")
                    .padding()
                    .background(.green, in: .capsule)
                    .transition(.move(edge: .top).combined(with: .opacity))
            }
            Spacer()
        }
    }
}
TransitionEffect
.opacityFade in and out (the default)
.slideIn from the leading edge, out to the trailing edge
.scaleGrow from and shrink to a point (.scale(scale: 0.5) to start bigger)
.move(edge: .bottom)In from and out to that edge
.asymmetric(insertion: .scale, removal: .opacity)Different effects for in and out
a.combined(with: b)Both at once

matchedGeometryEffect

matchedGeometryEffect makes two different views look like one view moving between places. Give both the same id in a shared @Namespace; when one is removed and the other inserted inside an animation, SwiftUI animates the frame from one to the other.

A small card grows into a large one. Typical use: a thumbnail expanding into a detail view.
struct HeroDemo: View {
    @Namespace private var animation
    @State private var expanded = false

    var body: some View {
        VStack {
            if expanded {
                RoundedRectangle(cornerRadius: 24)
                    .fill(.indigo)
                    .matchedGeometryEffect(id: "card", in: animation)
                    .frame(height: 300)
            } else {
                RoundedRectangle(cornerRadius: 12)
                    .fill(.indigo)
                    .matchedGeometryEffect(id: "card", in: animation)
                    .frame(width: 100, height: 100)
            }
        }
        .onTapGesture {
            withAnimation(.spring) { expanded.toggle() }
        }
    }
}

Try “Transitions and matchedGeometryEffect” with live code →

Codable and JSON

Codable is a type alias for Encodable & Decodable. An Encodable type can be turned into an external format (JSON, a property list); a Decodable type can be built from one. If every stored property is Codable (String, Int, Double, Bool, Date, URL, UUID, arrays, dictionaries, optionals and other Codable types), Swift synthesises the conformance: you only write : Codable.

Encode to Data, decode back. try because both can throw.
import Foundation

struct Habit: Codable {
    var name: String
    var streak: Int
}

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try encoder.encode(Habit(name: "Read", streak: 3))
print(String(decoding: data, as: UTF8.self))   // {"name":"Read","streak":3}

let decoded = try JSONDecoder().decode(Habit.self, from: data)
print(decoded.name, decoded.streak)            // Read 3

CodingKeys: renaming keys

When the JSON's key names differ from your property names (for example roll_no), declare a nested enum named exactly CodingKeys, with String raw values, conforming to CodingKey. Each case is a property; its raw value is the JSON key. Leave a property out of CodingKeys and it isn't encoded or decoded (so it needs a default value).

Renamed keys, an ISO 8601 date and an optional that is absent from the JSON.
import Foundation

struct Student: Codable {
    var name: String
    var rollNumber: Int
    var joined: Date
    var email: String?

    enum CodingKeys: String, CodingKey {
        case name
        case rollNumber = "roll_no"
        case joined = "joined_on"
        case email
    }
}

let json = """
{"name": "Asha", "roll_no": 21, "joined_on": "2025-07-01T09:00:00Z"}
"""

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
    let student = try decoder.decode(Student.self, from: Data(json.utf8))
    print(student.name, student.rollNumber, student.email == nil)   // Asha 21 true
} catch DecodingError.keyNotFound(let key, _) {
    print("Missing key:", key.stringValue)
} catch {
    print("Decoding failed:", error)
}

The CodingKeys enum is an ordinary String-backed enum. Its raw values are the keys:

enum CodingKeys: String, CaseIterable {
    case name
    case rollNumber = "roll_no"
    case joined = "joined_on"
}

for key in CodingKeys.allCases {
    print(key, "->", key.rawValue)
}
print(CodingKeys(rawValue: "roll_no") == .rollNumber)
print(CodingKeys(rawValue: "rollNumber"))

Output

name -> name
rollNumber -> roll_no
joined -> joined_on
true
nil

Dates and errors

The same do/catch pattern in plain Swift, with our own error enum standing in for DecodingError:

enum ParseError: Error {
    case keyNotFound(String)
    case typeMismatch(String)
}

struct Student {
    var name: String
    var rollNumber: Int
}

func parse(_ fields: [String: String]) throws -> Student {
    guard let name = fields["name"] else { throw ParseError.keyNotFound("name") }
    guard let text = fields["roll_no"] else { throw ParseError.keyNotFound("roll_no") }
    guard let roll = Int(text) else { throw ParseError.typeMismatch("roll_no") }
    return Student(name: name, rollNumber: roll)
}

let inputs: [[String: String]] = [
    ["name": "Asha", "roll_no": "21"],
    ["name": "Ravi"],
    ["name": "Meera", "roll_no": "twenty"],
]
for fields in inputs {
    do {
        let s = try parse(fields)
        print("ok:", s.name, s.rollNumber)
    } catch ParseError.keyNotFound(let key) {
        print("missing key:", key)
    } catch {
        print("other error:", error)
    }
}
print((try? parse(["name": "Kabir"]))?.name ?? "try? gave nil")

Output

ok: Asha 21
missing key: roll_no
other error: typeMismatch("roll_no")
try? gave nil
This doesn't compile
struct Student {
    var name: String
    var rollNumber: Int
}
let student = Student(name: "Asha", rollNumber: 21)   // e.g. the result of decode
student.rollNumber = 22

A struct stored in a let is immutable, including its var properties. Decode into a var if you need to edit the value.

Try “Codable and JSON” with live code →

Choosing where to store data

@AppStorage and UserDefaults

UserDefaults is a small key-value store for settings. @AppStorage is a SwiftUI property wrapper over it: reading gives the stored value (or the default), writing saves it and refreshes any view using it.

Settings that survive relaunches, in three lines.
struct SettingsView: View {
    @AppStorage("username") private var username = ""
    @AppStorage("dailyGoal") private var dailyGoal = 3
    @AppStorage("useMetric") private var useMetric = true

    var body: some View {
        Form {
            TextField("Name", text: $username)
            Stepper("Daily goal: \(dailyGoal)", value: $dailyGoal, in: 1...10)
            Toggle("Metric units", isOn: $useMetric)
        }
    }
}
// Outside SwiftUI: UserDefaults.standard.set(5, forKey: "dailyGoal")
//                  UserDefaults.standard.integer(forKey: "dailyGoal")

A JSON file in the documents directory

For a list of user data that isn't too large, encode it with JSONEncoder and write the Data to a file in the app's documents directory. Read and decode it at launch.

Save and load an array of Codable notes. .atomic writes to a temporary file first, so a crash can't leave half a file.
import Foundation

struct Note: Codable, Identifiable {
    var id = UUID()
    var text: String
}

enum NoteStore {
    static let url = URL.documentsDirectory.appending(path: "notes.json")   // iOS 16+

    static func save(_ notes: [Note]) throws {
        let encoder = JSONEncoder()
        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
        let data = try encoder.encode(notes)
        try data.write(to: url, options: .atomic)
    }

    static func load() -> [Note] {
        guard let data = try? Data(contentsOf: url) else { return [] }   // first launch: no file yet
        return (try? JSONDecoder().decode([Note].self, from: data)) ?? []
    }
}
UserDefaults / @AppStorageJSON file + CodableSwiftData (iOS 17)Core Data
Best forSmall settingsOne list or document, moderate sizeMany related records, queriesThe same, older apps, iOS 16 and earlier
Data modelKey → simple valueYour Codable structs@Model classesEntities in a .xcdatamodeld file + NSManagedObject
Queries / sortingNoneLoad everything, filter in memory@Query with #Predicate and sortNSFetchRequest / @FetchRequest
RelationshipsNoNesting onlyYes, with delete rulesYes, with delete rules
SavingImmediateYou write the fileAutosaveCall save() on the context
Code neededLeastLittleLittleMost

Try “Choosing where to store data” with live code →

SwiftData

SwiftData (iOS 17) is Apple's Swift-first persistence framework, built on the same storage engine as Core Data but declared entirely in code with macros. Four pieces:

PieceWhat it does
@Model on a classMakes it a persisted model (and observable, so views refresh)
.modelContainer(for: Habit.self)Creates the database for those models and puts a context in the environment
@Environment(\.modelContext)The context: insert, delete, save
@QueryFetches models into a view and keeps the array up to date
Two models with a one-to-many relationship.
import SwiftData
import Foundation

@Model
final class Habit {
    @Attribute(.unique) var name: String
    var createdAt: Date
    var isArchived: Bool
    @Relationship(deleteRule: .cascade, inverse: \CheckIn.habit)
    var checkIns: [CheckIn] = []

    init(name: String, createdAt: Date = .now, isArchived: Bool = false) {
        self.name = name
        self.createdAt = createdAt
        self.isArchived = isArchived
    }
}

@Model
final class CheckIn {
    var date: Date
    var habit: Habit?

    init(date: Date) {
        self.date = date
    }
}
Container on the WindowGroup, context from the environment, a filtered and sorted @Query.
import SwiftUI
import SwiftData

@main
struct HabitsApp: App {
    var body: some Scene {
        WindowGroup {
            HabitListView()
        }
        .modelContainer(for: Habit.self)      // CheckIn is found through the relationship
    }
}

struct HabitListView: View {
    @Environment(\.modelContext) private var context
    @Query(filter: #Predicate<Habit> { !$0.isArchived },
           sort: \Habit.createdAt, order: .reverse)
    private var habits: [Habit]

    var body: some View {
        NavigationStack {
            List {
                ForEach(habits) { habit in
                    Text(habit.name)
                }
                .onDelete { offsets in
                    for index in offsets {
                        context.delete(habits[index])
                    }
                }
            }
            .navigationTitle("Habits")
            .toolbar {
                Button("Add", systemImage: "plus") {
                    context.insert(Habit(name: "Habit \(habits.count + 1)"))
                }
            }
        }
    }
}

#Preview {
    HabitListView()
        .modelContainer(for: Habit.self, inMemory: true)
}

What a @Query with a filter and sort returns is what this plain-Swift code computes. The difference is that SwiftData runs it in the database and keeps it updated:

struct HabitRow {
    var name: String
    var day: Int          // day it was created
    var isArchived: Bool
}

let all = [
    HabitRow(name: "Read", day: 3, isArchived: false),
    HabitRow(name: "Walk", day: 5, isArchived: false),
    HabitRow(name: "Code", day: 1, isArchived: true),
    HabitRow(name: "Meditate", day: 4, isArchived: false),
]

// @Query(filter: #Predicate { !$0.isArchived }, sort: \.day, order: .reverse)
let shown = all.filter { !$0.isArchived }.sorted { $0.day > $1.day }
print(shown.map { $0.name })

// sort: [SortDescriptor(\.name)]
print(all.sorted { $0.name < $1.name }.map { $0.name })

Output

["Walk", "Meditate", "Read"]
["Code", "Meditate", "Read", "Walk"]

Try “SwiftData” with live code →

Bug hunt: lifecycle

A notes screen with five lifecycle mistakes. Name each problem and its fix before revealing.

Five defects: none stops the build, all show up in use.
import SwiftUI

struct NotesScreen: View {
    @Environment(\.scenePhase) private var scenePhase
    @State private var notes: [String] = []
    @State private var draft = ""

    var body: some View {
        List(notes, id: \.self) { Text($0) }
            .onAppear {
                Task { notes = await downloadNotes() }           // [A]
            }
            .onAppear {
                notes.append("Welcome back!")                    // [B]
            }
            .onChange(of: draft) { newValue in                   // [C]
                print("typing", newValue)
            }
            .onChange(of: scenePhase) { _, phase in
                switch phase {
                case .active: print("active")
                case .inactive: print("inactive")
                case .background: print("background")
                }                                                // [D]
            }
            .onChange(of: scenePhase) { _, phase in
                if phase == .inactive { saveNotes() }           // [E]
            }
    }

    func downloadNotes() async -> [String] {
        try? await Task.sleep(for: .seconds(2))
        return ["Buy milk", "Lab viva"]
    }

    func saveNotes() { print("saved", notes.count) }
}
Show the bugs
  • [A] A Task created in onAppear isn't tied to the view: it keeps running after the user leaves, and it starts again on every return. Fix: Use .task { notes = await downloadNotes() }, which is cancelled when the view disappears; skip the download if the notes are already loaded.
  • [B] onAppear runs every time the view appears, so returning to the screen appends another "Welcome back!" row (and with id: .self, duplicate rows share an id). Fix: Guard one-time work with a flag, or show the welcome as separate UI instead of data.
  • [C] The one-parameter onChange closure is deprecated in iOS 17. Fix: .onChange(of: draft) { _, newValue in ... } or the zero-parameter form.
  • [D] ScenePhase comes from the SDK and may gain cases; the switch draws a warning about unknown values. Fix: Add @unknown default: break.
  • [E] Saving only on .inactive also fires for a notification banner or Control Centre, and saving is what matters before suspension. Fix: Save on .background (optionally pause on .inactive).

Try “Bug hunt: lifecycle” with live code →

Exam traps

Code or claimWhat really happens
onAppearRuns every time the view appears, not once
.task { } when the view disappearsCancelled automatically
.task(id: query) when query changesOld task cancelled, new one started
.onChange(of: x) { newValue in }Deprecated in iOS 17: use { old, new in } or { }
.onChange when set to the same valueDoesn't run: only real changes
Going to backgroundactive → inactive → background
.animation(.spring) without value:Deprecated: write .animation(.spring, value: x)
.transition(.slide) without withAnimationNo transition: the view just appears
Default transition.opacity (fade)
matchedGeometryEffect idsSame id in the same @Namespace
CodableEncodable & Decodable
decode(Habit, from: data)Wrong: pass the type, Habit.self
Missing key for a non-optional propertyDecodingError.keyNotFound
Missing key for an optional propertyDecodes as nil
Default JSON key orderNot guaranteed: add .sortedKeys
Date with the default strategyA number, not an ISO string: set .iso8601
Big arrays in UserDefaultsWrong tool: use a file or SwiftData
@Model struct HabitWrong: @Model needs a class
@Query without .modelContainerCrash: no model context in the environment
Default delete rule.nullify; use .cascade to delete children
onAppear on rows inside a ForEach in a ListFires per row, lazily as rows scroll in
View hidden with .opacity(0)No onDisappear: it's still in the hierarchy; if removes it
Presenting a .sheetThe presenting view's onDisappear doesn't run
switch scenePhase with only three casesWarning: add @unknown default

Viva questions and answers

onAppear vs task?

onAppear is synchronous and runs every time the view appears. .task runs async work before the view appears and is cancelled automatically when the view disappears.

What is task(id:) for?

It restarts the task whenever the id value changes, cancelling the previous run. It's useful for searching as the user types or reloading when a selection changes.

How does onChange work in iOS 17?

.onChange(of: value) { oldValue, newValue in } runs when the Equatable value changes. There's also a zero-parameter form, and initial: true runs it on first appearance too.

What is scenePhase?

An environment value with three states: active, inactive and background. Apps watch it to pause work when inactive and save data when moving to the background.

Implicit vs explicit animation?

Implicit: .animation(_:value:) on a view animates that view whenever the value changes. Explicit: withAnimation { } animates every view affected by the state change inside the closure.

What is a transition?

How a view animates when it is inserted into or removed from the hierarchy, such as .opacity, .slide, .scale or .move(edge:). It only plays when the change happens inside an animation.

What does matchedGeometryEffect do?

It links two views with the same id in a shared @Namespace, so when one replaces the other inside an animation, SwiftUI animates the size and position between them.

What is Codable?

A type alias for Encodable and Decodable. If all stored properties are Codable, Swift synthesises the conformance, so JSONEncoder and JSONDecoder can convert the type to and from JSON.

What are CodingKeys?

A nested String enum conforming to CodingKey that maps property names to the external key names. Properties left out of it are not encoded or decoded.

How do you handle decoding errors?

Wrap try decoder.decode in do/catch and catch DecodingError cases such as keyNotFound and typeMismatch to show a useful message. try? hides the reason.

How do you decode ISO 8601 dates?

Set decoder.dateDecodingStrategy = .iso8601. By default Date is encoded as a number of seconds, not a string.

UserDefaults vs files vs SwiftData?

UserDefaults for small settings. A Codable JSON file for one moderate-size document or list. SwiftData for many records you need to query, sort and relate.

What is @AppStorage?

A SwiftUI property wrapper that reads and writes a UserDefaults key and refreshes the view when it changes. It supports simple types like Bool, Int, Double, String, URL and Data.

What are the main parts of SwiftData?

@Model classes define the schema, .modelContainer creates the store, the modelContext inserts and deletes, and @Query fetches data into views and keeps it updated.

Why is @Model a class, not a struct?

A persisted record has an identity and is shared: several views and the context must see the same object and its changes. That needs reference semantics.

What is a delete rule?

It says what happens to related objects when one is deleted. .cascade deletes them too; .nullify (the default) just clears their reference.

SwiftData vs Core Data?

SwiftData (iOS 17) declares models in Swift code with macros and integrates with SwiftUI through @Query. Core Data uses a visual model file and NSManagedObject subclasses, needs more code, and works on older iOS versions.

When does onAppear run for rows in a List?

Per row, when each row is about to appear, because List builds rows lazily. Scrolling away and back runs it again. In a non-lazy VStack every row appears at once.

Does presenting a sheet call the presenting view's onDisappear?

No. A standard sheet leaves the presenting view in place, so neither its onDisappear nor a second onAppear runs. Use the sheet's onDismiss for follow-up work.

What do you log when pushing and popping in a NavigationStack?

Push: the detail appears and the root disappears. Pop: the detail disappears and the root appears again. The order within each step isn't guaranteed, so code mustn't depend on it.

@unknown default vs default for ScenePhase?

Both compile. @unknown default handles future cases but still warns when a new SDK adds one you haven't listed; default silently absorbs them.

Quiz

  1. Which modifier runs async work and cancels it automatically when the view disappears?

    Show the answer

    .task

  2. What does .task(id: query) do when query changes?

    Show the answer

    Cancels the running task and starts a new one

  3. In iOS 17, which onChange closure form is current?

    Show the answer

    { oldValue, newValue in }

    The one-parameter form is deprecated in iOS 17; the zero-parameter form { } is also current.

  4. How many times does onAppear run if the user pushes a detail screen and comes back twice?

    Show the answer

    Three times

    Once at first, then once on each return.

  5. Which scene phase means the app is visible but not receiving input?

    Show the answer

    .inactive

  6. Where is the best place to save data when the app is leaving the screen?

    Show the answer

    When scenePhase becomes .background

  7. What is the difference between .animation(_:value:) and withAnimation?

    Show the answer

    The first is attached to a view; the second wraps the state change

  8. A view with .transition(.slide) is inserted by show.toggle() with no animation. What happens?

    Show the answer

    It appears instantly

    Transitions only play when the insertion happens inside an animation.

  9. Which transition uses different effects for appearing and disappearing?

    Show the answer

    .asymmetric(insertion:removal:)

  10. What does matchedGeometryEffect need?

    Show the answer

    The same id in a shared @Namespace

  11. What is Codable?

    Show the answer

    A type alias for Encodable & Decodable

  12. JSON uses the key roll_no but your property is rollNumber. What do you add?

    Show the answer

    A CodingKeys enum with case rollNumber = "roll_no"

    Or set keyDecodingStrategy = .convertFromSnakeCase on the decoder.

  13. A non-optional property's key is missing from the JSON. What happens?

    Show the answer

    decode throws DecodingError.keyNotFound

  14. Which outputFormatting gives readable JSON with keys in a stable order?

    Show the answer

    [.prettyPrinted, .sortedKeys]

  15. What is the right place for a user's 'dark mode' preference?

    Show the answer

    @AppStorage

  16. Which attribute stops two models from sharing the same value of a property?

    Show the answer

    @Attribute(.unique)

  17. Where is .modelContainer(for: Habit.self) usually attached?

    Show the answer

    On the WindowGroup in the App

  18. With @Relationship(deleteRule: .cascade) on habit.checkIns, deleting a habit…

    Show the answer

    Deletes its check-ins too

    .nullify, the default, would set habit to nil instead.

  19. Do you have to call context.save() after context.insert in a typical SwiftData app?

    Show the answer

    No: the main context autosaves; call save() only to write immediately

  20. A List of 300 rows has .onAppear { print(n) } on each row. Roughly how many lines print at launch?

    Show the answer

    About one screenful

    List creates rows lazily, so only rows about to be shown appear.

  21. A view is hidden with .opacity(0). Does its onDisappear run?

    Show the answer

    No

    It is still in the view hierarchy. Use if to remove it.

  22. Screen A presents a .sheet. Which of A's modifiers runs?

    Show the answer

    Neither

  23. Why add @unknown default to a switch over ScenePhase?

    Show the answer

    The SDK enum may gain cases in future

← Navigation and presentation · Swift Charts →

Practise this lesson interactively →