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
- Choose between onAppear, task, task(id:) and onChange, and react to scenePhase
- Animate with
.animation(_:value:)orwithAnimation, and add transitions to views that appear and disappear - Make types Codable, rename keys with CodingKeys and handle decoding errors
- Pick the right storage: @AppStorage, a JSON file, or SwiftData
- Build a SwiftData app with @Model, .modelContainer, @Query, insert and delete
Contents
- View lifecycle
- App lifecycle and scenePhase
- Predict the console: lifecycle experiments
- Animations
- Transitions and matchedGeometryEffect
- Codable and JSON
- Choosing where to store data
- SwiftData
- 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.
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)"
}
}| Modifier | Runs | Async? | Cancelled automatically? |
|---|---|---|---|
.onAppear { } | Each time the view appears | No (synchronous) | Not applicable |
.onDisappear { } | Each time the view disappears | No | Not applicable |
.task { } | Before the view appears | Yes: you can await | Yes, when the view disappears |
.task(id: value) { } | On appear, and again whenever value changes | Yes | Yes: 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) | No | Not 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
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.
.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.
struct Scoreboard {
var score = 0 {
didSet { print("changed", oldValue, "->", score) }
}
}
var board = Scoreboard()
board.score = 5
board.score += 2
board.score = 7Show the answer
changed 0 -> 5
changed 5 -> 7
changed 7 -> 7App 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.
@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")
}
}
}
}| ScenePhase | Meaning | Typical reaction |
|---|---|---|
.active | On screen and receiving input | Refresh data, resume timers |
.inactive | Visible but not interactive (app switcher, an incoming call banner, Control Centre) | Pause games and timers |
.background | Not visible; may be suspended soon | Save 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
nothingSwitching over the real ScenePhase
.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.
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) }
}
}
}
}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") }
}
}
}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") }
}
}
}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") }
}
}
}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".
.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 to | A view | The code that changes state |
| Animates | Changes to that view (and its children) when value changes | Every view affected by the state changed inside the closure |
| Good for | One view that always animates the same way | A button action; insertions and removals; several views at once |
| Watch out | Needs value:; the old .animation(_:) without it is deprecated | Only changes made inside the closure animate |
Curves
.linear: constant speed. Good for spinners..easeIn,.easeOut,.easeInOut: slow at the start, end, or both..easeInOut(duration: 0.6)sets the time..defaultis an ease-in-out curve..spring: physics-based, may overshoot a little. iOS 17 adds.spring(duration:bounce:)and the presets.smooth,.snappyand.bouncy.- Modifiers on an animation:
.delay(0.2),.speed(2),.repeatCount(3),.repeatForever(autoreverses: true).
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.0A 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.
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.
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()
}
}
}| Transition | Effect |
|---|---|
.opacity | Fade in and out (the default) |
.slide | In from the leading edge, out to the trailing edge |
.scale | Grow 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.
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.
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 3JSONEncoder().encode(value)returnsData;JSONDecoder().decode(Type.self, from: data)returns the value. Note the.self: you pass the type itself.outputFormatting = [.prettyPrinted, .sortedKeys]gives indented JSON with keys in alphabetical order, which makes files readable and diffs stable. Without.sortedKeysthe key order isn't guaranteed.- An optional property that is missing from the JSON decodes as
nil. A missing non-optional property is an error. - Extra keys in the JSON that the type doesn't declare are ignored.
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).
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
nilDates and errors
- By default
Dateis encoded as a number (seconds since 1 January 2001). SetdateDecodingStrategy = .iso8601(anddateEncodingStrategy = .iso8601) for strings like2025-07-01T09:00:00Z. - Decoding throws
DecodingError:.keyNotFound(missing key),.typeMismatch(a string where a number was expected),.valueNotFound(nullfor a non-optional) and.dataCorrupted(invalid JSON or a bad date). - Use
do { try ... } catch { }and show a useful message;try?turns any failure intoniland hides why.
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 nilstruct Student {
var name: String
var rollNumber: Int
}
let student = Student(name: "Asha", rollNumber: 21) // e.g. the result of decode
student.rollNumber = 22A struct stored in a let is immutable, including its var properties. Decode into a var if you need to edit the value.
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.
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")- Supported types:
Bool,Int,Double,String,URL,Data, and enums withIntorStringraw values. - Keep it small: preferences, flags such as
hasSeenOnboarding. It isn't a database and isn't secure: never put passwords or tokens there (use the Keychain).
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.
.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 / @AppStorage | JSON file + Codable | SwiftData (iOS 17) | Core Data | |
|---|---|---|---|---|
| Best for | Small settings | One list or document, moderate size | Many related records, queries | The same, older apps, iOS 16 and earlier |
| Data model | Key → simple value | Your Codable structs | @Model classes | Entities in a .xcdatamodeld file + NSManagedObject |
| Queries / sorting | None | Load everything, filter in memory | @Query with #Predicate and sort | NSFetchRequest / @FetchRequest |
| Relationships | No | Nesting only | Yes, with delete rules | Yes, with delete rules |
| Saving | Immediate | You write the file | Autosave | Call save() on the context |
| Code needed | Least | Little | Little | Most |
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:
| Piece | What it does |
|---|---|
@Model on a class | Makes 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 |
@Query | Fetches models into a view and keeps the array up to date |
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
}
}@Modelgoes on a class, not a struct: models are shared, identified objects that the context tracks. The class needs aninit.@Attribute(.unique): no two habits can have the same name. Inserting a second one with an existing name updates the existing record instead of adding a duplicate (an "upsert").@Relationship(deleteRule: .cascade): deleting a habit deletes its check-ins. The default rule,.nullify, would leave them withhabitset tonil.inverse:links the two sides, so settingcheckIn.habitand appending tohabit.checkInsstay in sync.
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)
}- Insert:
context.insert(model). Delete:context.delete(model). Update: just change a property:habit.name = "Walk". - Save: the context from
.modelContainerautosaves (after changes and when the app goes to the background). Calltry context.save()when you need it written immediately. - @Query re-runs when the data changes, so the list updates by itself.
sort:takes a key path (withorder:) or an array ofSortDescriptors;filter:takes a#Predicate. #Predicateis a macro that turns a closure into a query the database can run. It supports comparisons,&&,||,!and some String methods such ascontains, but not arbitrary function calls.inMemory: truein previews gives a fresh, empty store that is never written to disk.
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"]Bug hunt: lifecycle
A notes screen with five lifecycle mistakes. Name each problem and its fix before revealing.
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
Taskcreated inonAppearisn'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]
onAppearruns every time the view appears, so returning to the screen appends another "Welcome back!" row (and withid: .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
onChangeclosure is deprecated in iOS 17. Fix:.onChange(of: draft) { _, newValue in ... }or the zero-parameter form. - [D]
ScenePhasecomes from the SDK and may gain cases; the switch draws a warning about unknown values. Fix: Add@unknown default: break. - [E] Saving only on
.inactivealso fires for a notification banner or Control Centre, and saving is what matters before suspension. Fix: Save on.background(optionally pause on.inactive).
Exam traps
| Code or claim | What really happens |
|---|---|
onAppear | Runs every time the view appears, not once |
.task { } when the view disappears | Cancelled automatically |
.task(id: query) when query changes | Old 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 value | Doesn't run: only real changes |
| Going to background | active → inactive → background |
.animation(.spring) without value: | Deprecated: write .animation(.spring, value: x) |
.transition(.slide) without withAnimation | No transition: the view just appears |
| Default transition | .opacity (fade) |
matchedGeometryEffect ids | Same id in the same @Namespace |
Codable | Encodable & Decodable |
decode(Habit, from: data) | Wrong: pass the type, Habit.self |
| Missing key for a non-optional property | DecodingError.keyNotFound |
| Missing key for an optional property | Decodes as nil |
| Default JSON key order | Not guaranteed: add .sortedKeys |
Date with the default strategy | A number, not an ISO string: set .iso8601 |
| Big arrays in UserDefaults | Wrong tool: use a file or SwiftData |
@Model struct Habit | Wrong: @Model needs a class |
@Query without .modelContainer | Crash: no model context in the environment |
| Default delete rule | .nullify; use .cascade to delete children |
onAppear on rows inside a ForEach in a List | Fires 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 .sheet | The presenting view's onDisappear doesn't run |
switch scenePhase with only three cases | Warning: 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
Which modifier runs async work and cancels it automatically when the view disappears?
Show the answer
.task
What does
.task(id: query)do whenquerychanges?Show the answer
Cancels the running task and starts a new one
In iOS 17, which
onChangeclosure 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.How many times does
onAppearrun if the user pushes a detail screen and comes back twice?Show the answer
Three times
Once at first, then once on each return.
Which scene phase means the app is visible but not receiving input?
Show the answer
.inactive
Where is the best place to save data when the app is leaving the screen?
Show the answer
When scenePhase becomes .background
What is the difference between
.animation(_:value:)andwithAnimation?Show the answer
The first is attached to a view; the second wraps the state change
A view with
.transition(.slide)is inserted byshow.toggle()with no animation. What happens?Show the answer
It appears instantly
Transitions only play when the insertion happens inside an animation.
Which transition uses different effects for appearing and disappearing?
Show the answer
.asymmetric(insertion:removal:)
What does
matchedGeometryEffectneed?Show the answer
The same id in a shared @Namespace
What is
Codable?Show the answer
A type alias for Encodable & Decodable
JSON uses the key
roll_nobut your property isrollNumber. What do you add?Show the answer
A CodingKeys enum with
case rollNumber = "roll_no"Or set
keyDecodingStrategy = .convertFromSnakeCaseon the decoder.A non-optional property's key is missing from the JSON. What happens?
Show the answer
decode throws DecodingError.keyNotFound
Which
outputFormattinggives readable JSON with keys in a stable order?Show the answer
[.prettyPrinted, .sortedKeys]
What is the right place for a user's 'dark mode' preference?
Show the answer
@AppStorage
Which attribute stops two models from sharing the same value of a property?
Show the answer
@Attribute(.unique)
Where is
.modelContainer(for: Habit.self)usually attached?Show the answer
On the WindowGroup in the App
With
@Relationship(deleteRule: .cascade)onhabit.checkIns, deleting a habit…Show the answer
Deletes its check-ins too
.nullify, the default, would sethabitto nil instead.Do you have to call
context.save()aftercontext.insertin a typical SwiftData app?Show the answer
No: the main context autosaves; call save() only to write immediately
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.
A view is hidden with
.opacity(0). Does itsonDisappearrun?Show the answer
No
It is still in the view hierarchy. Use
ifto remove it.Screen A presents a
.sheet. Which of A's modifiers runs?Show the answer
Neither
Why add
@unknown defaultto a switch overScenePhase?Show the answer
The SDK enum may gain cases in future