The problem
A text field loses what you typed when a parent re-renders. A sheet’s scroll position jumps back to the top. A row’s body runs forty times while you scroll, and nothing on screen changed. These look like unrelated bugs, but each one comes from two questions SwiftUI asks on every update: is this the same view as before, and did anything it depends on change? Once you can answer those questions for your own code, both the state bugs and the performance bugs become traceable.
Identity, lifetime and dependencies
Apple’s Demystify SwiftUI session names the three things SwiftUI looks at. Identity decides whether two view values across updates represent the same element. Lifetime is how long that identity exists. Dependencies decide when a view’s body needs to run again.
View values themselves are short-lived. body produces fresh structs on every update, SwiftUI compares them with the previous ones and throws them away. Chris Eidhof’s talk A Day in the Life of a SwiftUI View frames it as two trees: an ephemeral view tree you build in body, and a persistent render tree, the attribute graph, that SwiftUI keeps and updates. @State lives in that persistent tree. Its initial value is used once, when the node is created, which is why changing the default in a parent does nothing to a child that already exists.
State lasts exactly as long as identity. Change the identity and SwiftUI destroys the node, its state and its running animations, then builds a new one from the initial values.
Structural identity
Most views never get an explicit ID. SwiftUI identifies them by their type and their position in the view hierarchy. An if/else produces a _ConditionalContent with two branches, and each branch has its own identity even if both branches contain the same view type.
import SwiftUI
struct Counter: View {
@State private var count = 0
var body: some View {
Button("Count: \(count)") { count += 1 }
}
}
struct ThemedCounter: View {
let isNight: Bool
var body: some View {
if isNight {
Counter().foregroundStyle(.white)
} else {
Counter()
}
}
}
Toggle isNight and the count resets to zero. The two Counter values sit in different branches, so they are different views. The Demystify session’s fix is an inert modifier: keep one view and vary a modifier argument.
struct ThemedCounterFixed: View {
let isNight: Bool
var body: some View {
Counter()
.foregroundStyle(isNight ? .white : .primary)
}
}
The session suggests asking whether you’re showing two different views or two states of one view. Default to one view with modifiers. Use a branch when the content really is different and a transition plus a state reset is what you want.
The conditional modifier extension
A common helper looks like this:
extension View {
@ViewBuilder
func `if`<T: View>(_ condition: Bool, transform: (Self) -> T) -> some View {
if condition { transform(self) } else { self }
}
}
It reads nicely and hides a branch. Every call site that passes a changing condition swaps the identity of the whole modified subtree, with all the state loss above. The session warns about exactly this: branches buried in helpers, possibly in another file, that change identity without anyone noticing. Prefer ternaries inside modifier arguments. The safe exception is a condition that can’t change at runtime, such as if #available.
AnyView
AnyView erases the type, and with it the structure SwiftUI uses for identity. The Demystify session lists the costs: lost structural information, worse diagnostics and potentially worse performance. Its replacement is a @ViewBuilder function with a switch, which keeps static types.
enum Attachment {
case photo(URL), document(String), location(Double, Double)
}
@ViewBuilder
func attachmentView(_ attachment: Attachment) -> some View {
switch attachment {
case .photo(let url): Text(url.lastPathComponent)
case .document(let name): Label(name, systemImage: "doc")
case .location(let lat, let lon): Text("\(lat), \(lon)")
}
}
The WWDC23 performance session adds a list-specific reason: inside ForEach, AnyView hides how many views each element produces, which forces List to build rows just to count them.
Explicit identity
You give identity explicitly with ForEach IDs and with .id(_:). The rules from Demystify SwiftUI are short: IDs must be stable and unique. Indices shift when you insert. A UUID() created in a computed property is new on every read. Duplicate values collide.
.id(_:) is also a tool. Changing the ID on purpose tears down the subtree and builds a fresh one, which is the cleanest way to reset an editor when the user switches documents:
struct DraftEditor: View {
let draftID: UUID
@State private var text = ""
var body: some View {
TextEditor(text: $text)
.task(id: draftID) {
text = "Loaded draft \(draftID.uuidString.prefix(4))"
}
}
}
struct EditorHost: View {
let selectedDraft: UUID
var body: some View {
DraftEditor(draftID: selectedDraft)
.id(selectedDraft)
}
}
Eidhof makes the counterpoint: if you only need to rerun work when a value changes, task(id:) or onChange(of:) does that without discarding the subtree’s state and animations. Reach for .id when you want the reset, and for task(id:) when you want the reload. Never use .id(UUID()) to force a refresh. It rebuilds the subtree on every update.
Why body runs again
A view’s dependencies are its inputs. The Demystify session lists them: properties passed by the parent, @State, @Binding, @Environment and observable models it reads. When one changes, SwiftUI creates a new view value and may run body.
For inputs passed by the parent, SwiftUI compares the old and new view values. Airbnb’s engineering team describes it in Understanding and Improving SwiftUI Performance: by default SwiftUI compares stored properties through reflection, value types field by field and reference types by identity. Closures can’t be compared reliably, so a view that stores one looks changed on every parent update.
Three fixes follow from this.
Pass less. The WWDC23 session shows a view that took a whole Dog but displayed only the image. Passing dog.image instead meant edits to the name no longer re-ran it. Extracting small subviews with narrow inputs has the same effect and makes dependencies visible at the call site.
Don’t store builder closures. Apple’s performance article says to call a content-building closure in the initializer and store the result. A stored closure that captures the parent’s self changes whenever any parent property changes.
struct Card<Content: View>: View {
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding()
.background(.background.secondary, in: .rect(cornerRadius: 16))
}
}
The article notes that action closures, like the one you pass to Button, and closures that take a parameter, like ForEach’s, don’t need this treatment.
Read observable properties narrowly. With @Observable, a view depends on the exact properties its body reads, including ones read inside computed properties and helper methods. A helper that walks a whole array makes the view depend on the whole array.
Debugging with Self._printChanges()
Self._printChanges() prints why SwiftUI ran a view’s body. Call it at the top of body:
struct ScoreView: View {
let player: String
@State private var score = 0
var body: some View {
#if DEBUG
let _ = Self._printChanges()
#endif
VStack {
Text(player)
Button("Score: \(score)") { score += 1 }
}
}
}
Antoine van der Lee explains the output in Debugging SwiftUI views. A property name such as _score means that dynamic property changed. @self means the view value itself changed, so the parent passed different inputs. @identity means the view’s identity changed and its persistent data was recycled for a new instance. A stream of @self lines for a view whose inputs look constant usually points at a stored closure or a reference type.
He also covers Self._logChanges(), added in Xcode 15.1, which writes the same information to the unified log under the com.apple.SwiftUI subsystem with the category “Changed Body Properties.” That is easier to filter in the Xcode console than print output. You can also run expression Self._printChanges() from LLDB while stopped at a breakpoint in body.
The WWDC23 session is clear about the limits. These are underscored debugging hooks with a runtime cost, they aren’t guaranteed to exist in future releases, and they must never ship. The #if DEBUG guard keeps them out of release builds.
Equatable views
When a view’s inputs include something SwiftUI can’t compare well, you can define the comparison yourself.
import SwiftUI
struct PriceTag: View, Equatable {
let amount: Decimal
let currencyCode: String
let onTap: () -> Void
nonisolated static func == (lhs: PriceTag, rhs: PriceTag) -> Bool {
lhs.amount == rhs.amount && lhs.currencyCode == rhs.currencyCode
}
var body: some View {
Button(action: onTap) {
Text(amount, format: .currency(code: currencyCode))
}
}
}
struct Checkout: View {
let total: Decimal
var body: some View {
PriceTag(amount: total, currencyCode: "EUR") { print("Pay") }
.equatable()
}
}
The == ignores the closure, so a parent re-render with the same amount skips PriceTag’s body. In the Swift 6 language mode, View makes the struct main-actor isolated, and nonisolated lets the operator satisfy Equatable. It reads only let properties of Sendable types, which is allowed.
Sources disagree on whether the conformance alone is enough. Airbnb’s write-up says SwiftUI uses an Equatable conformance in place of reflection. Javier Nigro found in The Mystery Behind View Equality that the conformance wasn’t always consulted, depending on the view’s other properties, and that wrapping with .equatable() made it reliable. He recommends always adding .equatable(), and so do I: the behavior without it is undocumented, and the modifier states your intent at the call site.
Two limits. Equatable only governs the inputs the parent passes. Environment values and observable properties that body reads are separate dependencies and still invalidate the view, as commenters on Javier’s post observed. And a wrong == is a correctness bug: leave out a property the body displays and the view stops updating when it changes. Airbnb generates conformances with a macro and marks skipped properties explicitly for that reason.
The SwiftUI instrument in Xcode 26
_printChanges tells you what changed for one view. Instruments tells you which updates cost time and why they happened across the app. The WWDC25 session Optimize SwiftUI performance with Instruments introduced a rebuilt SwiftUI instrument in Instruments 26. You need Xcode 26 and a device on a current OS that supports SwiftUI trace recording. Profile on the device, not the Simulator.
Choose Product > Profile, pick the SwiftUI template and record a deferred trace while you exercise the screen. The SwiftUI track has these lanes, as Apple’s performance article describes them:
| Lane | What it shows |
|---|---|
| Update Groups | When SwiftUI is doing work at all. CPU busy with this lane empty means the cost is outside SwiftUI. |
| Long View Body Updates | Body evaluations over 500 microseconds in orange, over 1,000 in red |
| Long Platform View Updates | Slow updates of UIKit or AppKit views hosted in SwiftUI |
| Other Long Updates | Other long work such as geometry and text layout |
Start with red updates during scrolling or interaction. The session notes that long updates while the first hierarchy builds at launch don’t necessarily cause hitches. Control-click a long update, choose Set Inspection Range and Zoom, and switch to Time Profiler to see which of your functions ran.
Many short updates are the other failure mode. Select an update group, hold the pointer over an update and choose Show Causes to open the cause-and-effect graph. Read it from left to right. Blue nodes are your code or user actions, such as a tap. Gray nodes are system objects. A state change node names the property and lets you see a backtrace of where it was set. Edges labeled update or creation explain why a body ran or why a view first appeared. A dimmed body node means the view was notified but its body didn’t run. External Environment and EnvironmentWriter nodes separate system environment changes, like color scheme, from ones your own .environment modifiers caused.
The WWDC25 case study is worth repeating because it is so common. Every row in a list depended on a whole favorites array through a helper method, so toggling one favorite re-ran every visible row. The graph showed the array as the cause for each row. Giving each item its own observable state cut the updates to the two rows that changed.
Apple’s article adds one caution: the graph shows one changing property per edge. After a fix, record again. Another cause may have been hiding behind the first.
Traps
- State in the wrong place.
@Statein a child that the parent recreates under a new identity resets. Move it up or pass it down. - Conditional modifiers. An
ifhelper changes identity. Ternaries in modifier arguments don’t. .idas a refresh button. It rebuilds everything below it. Change the data instead.AnyViewin rows. It hides structure from identity and fromList’s row counting.- Formatters and filtering in
body. They make every update slow. Cache them in the model. - Frequently changing environment values. Every view that reads the environment gets checked when any value changes, per the WWDC25 session. Keep timers and geometry out of it.
- Debug hooks in release. Guard
_printChangesand_logChangeswith#if DEBUG.
Checklist
- Each view is either two different views (branch) or one view in two states (modifier). Pick on purpose.
ForEachIDs are stable and unique..idappears only where a reset is intended.- No
AnyViewwhere a@ViewBuilderswitch works. - Child views receive the narrowest values they display.
- Builder closures are called in
initand the result stored. - Views with closure inputs that re-render too often get a hand-written
==and.equatable(). _printChangesconfirms the change you expect, then the SwiftUI instrument confirms the cost on a device.
Sources and further reading
- Demystify SwiftUI (WWDC21) Apple
- Demystify SwiftUI performance (WWDC23) Apple
- Optimize SwiftUI performance with Instruments (WWDC25) Apple
- Understanding and improving SwiftUI performance Apple Developer Documentation
- A Day in the Life of a SwiftUI View Chris Eidhof
- Debugging SwiftUI views: what caused that change? Antoine van der Lee, SwiftLee
- The Mystery Behind View Equality Javier Nigro, The SwiftUI Lab
- Understanding and Improving SwiftUI Performance Airbnb Engineering