Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 46 ยท State and Data Flow

Common SwiftUI Pitfalls

Learn the SwiftUI bugs that bite most often: state changes in body, the wrong property wrapper, heavy body code, AnyView, unstable ids and retain cycles.

Most SwiftUI bugs are not exotic. The same handful of mistakes account for the screens that freeze, flicker, reset or leak memory. They almost always trace back to one idea from this chapter: body is a pure description of the UI for the current state, and it runs far more often than you think. Code that violates that, by changing state, doing heavy work or creating new identities inside body, produces strange behavior.

This lesson is a field guide. For each pitfall you will see the symptom, why it happens and the fix. SwiftUI itself cannot run on the site, so the SwiftUI snippets are read-only, and three stand-ins in plain Swift reproduce the underlying mechanics so you can run them. It builds on identity and lifecycle and choosing property wrappers.

Six habits to avoid

State in body Changing state while drawing loops.
Wrong wrapper Copies instead of shared state.
Heavy body Sorting and parsing on every update.
1 / 2

Changing state during a view update

Symptom: a console warning that reads like "Modifying state during view update, this will cause undefined behavior", a screen that flickers, or a UI that locks up in an update loop.

Why: SwiftUI calls body, compares the result, and redraws. If body itself changes state, SwiftUI has to call body again, which changes state again, and so on.

Swift
struct Bad: View {
    @State private var count = 0

    var body: some View {
        count += 1                    // mutation while computing the view
        return Text("Rendered \(count) times")
    }
}

Fix: state changes belong in event handlers (Button actions, onChange, task, onAppear), never in body or in the computed properties it calls. If a value can be derived from other state, compute it and do not store it.

The stand-in models the loop with a tiny update scheduler: a render that changes state marks the model dirty and forces another pass. A pass limit stops the run so you can see it.

Swift Why mutating state in body loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The bad version never settles; only the artificial limit stops it. The good version renders once because body only reads.

Using the wrong property wrapper

Symptom: edits in a child view do not reach the parent, a value resets when the parent updates, or a model changes but the UI does not.

Why and fix:

  • A child with @State var value that the parent also holds has two copies. Use @Binding.
  • @State initialized from an init parameter takes the value once and ignores later changes. Use a plain let, or a @Binding if the child edits it.
  • A plain class in @State whose properties change will not refresh the UI. Mark it @Observable.
  • An @Observable model created inside body is replaced on every update. The owner must keep it in @State (or the app must inject it).
Swift
struct Parent: View {
    var body: some View {
        Child(model: Model())      // new Model on every update of Parent
    }
}

struct Parent2: View {
    @State private var model = Model()   // one instance, kept across updates

    var body: some View {
        Child(model: model)
    }
}

The full decision guide is in Choosing the Right Property Wrapper.

A heavy body

Symptom: typing in a field is laggy, scrolling stutters, the app feels warm.

Why: body can run many times per second during an animation, a drag or typing. Anything expensive you put in it runs each time: sorting a big array, filtering, parsing JSON, creating a DateFormatter or NumberFormatter, building images.

Swift
var body: some View {
    let sorted = items.sorted { $0.score > $1.score }          // runs on every update
    let formatter = DateFormatter()                              // expensive to create
    formatter.dateStyle = .medium
    return List(sorted) { Text(formatter.string(from: $0.date)) }
}

Fix: compute once when the input changes (in the model, or with onChange), keep formatters in a shared constant, or use the format styles built into Text (Text(date, format: .dateTime.day().month())). Keep body to cheap layout and reads. Measuring the real cost is covered in Performance and Instruments.

AnyView and type erasure

Symptom: animations behave oddly, state resets when you did not expect it, and long lists get slower.

Why: SwiftUI compares the types in your view tree to work out what changed. AnyView erases that type information, so SwiftUI has less to go on and may rebuild more than necessary. It is not forbidden, but it is rarely the best tool.

Swift
func row(for item: Item) -> AnyView {          // avoid
    if item.isNew { return AnyView(NewRow(item)) }
    return AnyView(PlainRow(item))
}

@ViewBuilder
func row(for item: Item) -> some View {          // prefer
    if item.isNew { NewRow(item) } else { PlainRow(item) }
}

@ViewBuilder, Group and generics keep the concrete structure visible. Reach for AnyView only when the type truly cannot be known at compile time.

Unstable or duplicate ids

Symptom: rows flash, scroll position is lost, state attaches to the wrong row, or the console reports duplicate ids.

Why: identity is the basis for keeping state (see the identity lesson). An id that changes on every update makes every row a new view.

Swift
ForEach(names.map { Row(id: UUID(), name: $0) }) { row in   // new ids every update
    Text(row.name)
}

Fix: store the id in the model, created once when the item is created, and make sure two items never share one. The stand-in counts how many rows survive an update with each approach (it uses a counter instead of UUID() so the output is the same every run).

Swift Stable ids keep rows, new ids rebuild them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With unstable ids none of the rows is recognized as the same, so every update destroys and recreates all of them, along with their state.

Retain cycles in closures

Symptom: a screen's model is never deallocated, a timer keeps firing after the user leaves, memory grows as you navigate back and forth.

Why: SwiftUI views are structs and do not form reference cycles by themselves. The cycles come from classes: a view model that stores a closure which captures the model strongly, a timer or notification observer registered with a strong capture, or a Combine/async callback that holds the object while the object holds the callback.

Swift
@Observable
final class SearchModel {
    var query = ""
    private var timer: Timer?

    func start() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
            self.refresh()               // the closure keeps self alive; self keeps the timer
        }
    }

    func refresh() { /* ... */ }
}

Fix: capture weakly ([weak self]) and unwrap, and cancel or invalidate on disappear. Prefer task, which cancels automatically, over hand-rolled timers and callbacks when you can. The next stand-in shows the difference with deinit, which prints when an object is really released.

Swift A closure that keeps its owner alive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The weak screen is released as soon as open returns. The strong one holds itself alive through its own closure, so its deinit never prints. In a real app that leak would stay in memory until the process ends.

A debugging tip: add a deinit { print(...) } to your view models during development. If you navigate away from a screen and the line does not appear, you have a leak. The Memory Graph debugger and Instruments (see Debugging Xcode Apps) show who is holding the object.

A quick checklist

Before you blame SwiftUI, check:

  1. Does body or anything it calls write to state? Move writes to handlers.
  2. Does each piece of data have one owner and the right wrapper?
  3. Is expensive work inside body? Move it out or cache it.
  4. Is AnyView hiding structure? Use @ViewBuilder or Group.
  5. Are ids stable, unique and based on the item, not its position?
  6. Do long-lived objects capture themselves strongly in stored closures?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is count += 1 inside body a bug?

    A state change schedules a new body evaluation, so a body that changes state keeps invalidating itself. Change state in event handlers.
  2. 2. Which is the best place to create a DateFormatter used by many rows?

    Formatters are expensive to create, and body can run many times per second.
  3. 3. What is the main downside of AnyView?

    Prefer @ViewBuilder, Group or generics when the structure can be known at compile time.
  4. 4. Where do retain cycles in SwiftUI apps usually come from?

    Structs do not form reference cycles by themselves. Stored closures on class instances do.
  5. 5. What goes wrong with ForEach rows whose ids are created with UUID() while building the rows?

    Identity must stay the same across updates for state to be preserved. Store the id in the model when the item is created.

Summary

  • body runs often and must only describe the UI. Do not change state, do heavy work or create identities in it.
  • Pick the right wrapper: one owner, others borrow with bindings, and make shared model classes @Observable.
  • Keep body cheap: cache sorted data, reuse formatters, and prefer @ViewBuilder over AnyView.
  • Use stable, unique, item-based ids stored in the model.
  • Break retain cycles with [weak self] and cancel work on disappear; check with a temporary deinit print.

Next, start the navigation chapter with NavigationStack and Navigation Paths.