swiftui · folio
In one line: SwiftUI keeps state and view lifetime per identity, and re-runs body only for
views whose dependencies changed. Fast SwiftUI = stable identity (state survives, diff is
cheap) + narrow dependencies (few bodies run) + cheap bodies (each run is fast).
Download PDF Print view LaTeX source
How it works
- Structural identity — a view’s type + position in the
bodytree.if/elsebecomes_ConditionalContent: the two branches are different slots, so switching branch = destroy one view, create the other (state gone,onAppearagain, transition plays). Two states of one view? Fold the condition into a value (picture); a.if(cond) { …}helper is a branch in disguise. - Explicit identity —
ForEachids (Identifiable/id: \.x) and.id(_:). A new.idvalue = a brand-new view: legit to reset a form or scroll view, costly if it changes every update. AnyViewerases the type, so SwiftUI cannot see the structure: when the wrapped type changes the whole subtree is replaced, and diffing is slower. Prefersome Viewand generics.- What invalidates
body: a@State/@Bindingit reads; anObservableObject’sobjectWillChange(any@Published— whole object); an@Observable(17) property it read during the lastbody(per property); an@Environmentvalue it reads; or new, non-equal inputs from the parent. - Skipping: SwiftUI compares a child’s inputs before calling its
body; closures and non-equatable fields defeat that.Equatableview +.equatable()lets your==decide — worth it only if==is cheap and complete (a missed field ⇒ stale UI). - Cheap body: no
DateFormatter(), sorting, filtering, image decode or I/O insidebodyorinit— precompute in the model, cache in astatic let, or load in.task(id:)(cancelled + restarted whenidchanges). @State var m = Model()evaluatesModel()on every view init and keeps only the first (@StateObjecttakes an autoclosure, run once): a heavy or side-effecting init ⇒ optional@State, created in.task.- Lazy rows:
LazyVStackbuilds rows on demand; a row scrolled away stops updating, is kept for a number of updates, then freed with its@State— keep row data in the model. Prefetch can run a row’sbodyand never callonAppear;onAppearre-fires on scroll-back, so guard paging withisLoading(example).VStackbuilds every row up front. - Measure:
let _ = Self._printChanges()inbody(DEBUG, prints@self,@identityor the property that changed). Instruments’ SwiftUI instrument (Xcode 26+): long-update lanes and a Cause & Effect graph; Xcode 27 also records why a layout was not cached. Pair with Time Profiler + Hangs.
Example — a lean, paged feed
@MainActor @Observable final class Feed {
var items: [Post] = []; var isLoading = false
func loadMore() async {
guard !isLoading else { return }; isLoading = true
defer { isLoading = false }
items += await api.page(after: items.last?.id) } }
struct FeedView: View { let feed: Feed
var body: some View {
List(feed.items) { post in // Identifiable, stable id
Row(title: post.title) // a value: Row redraws only
.task { // when its title changes
if post.id == feed.items.last?.id {
await feed.loadMore() } }
} } }
Identity & dependencies
Traps
ForEach(items, id: \.self)on mutable values, array indices, orUUID()made inbody— every row looks new: lost row state, wrong animations, duplicate-id glitches. Use a stable, entity-owned id.- “
@Observablefixes everything” — a row whoseisFavorite(item)scans the whole favorites array depends on all of it: one new favorite re-runs every row’sbody. Give rows a per-item model or plain values. Computed properties count as reads of what they touch. .id(UUID())or an.idtied to often-changing data silently rebuilds the subtree (and a wrappedUIView) on every update.VStackof 10 000 rows inside aScrollView— eager; useListorLazyVStack.