Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 46 ยท State and Data Flow

View Identity and Lifecycle

Understand structural and explicit identity in SwiftUI, why @State resets, and how onAppear, task, onChange and id() behave, with runnable stand-ins.

A SwiftUI view is a small struct that is thrown away and recreated constantly. If that is true, how does a @State counter keep its value, and why does it sometimes reset to zero when you did not expect it to? The answer is identity. SwiftUI decides, on every update, which new view is "the same view" as one from the previous update. The same view keeps its state; a different view starts fresh.

Lifecycle in SwiftUI therefore does not mean "init, viewDidLoad, deinit" as in UIKit. It means: a view with a given identity appears, changes and disappears. This lesson explains the two kinds of identity, the modifiers that react to appearing, changing and disappearing, and the most common bug in this area: state that resets for no visible reason. It builds on the SwiftUI mental model and @State and @Binding.

Same identity, same view

Identity How SwiftUI knows a view is the same one.
State Stored per identity, not in the struct.
Structs Recreated often; they hold no state themselves.
1 / 2

Structural identity

When you write a view body, SwiftUI builds a tree. Each view's identity comes from where it sits in that tree. In an if/else, the two branches are different positions, even if they contain the same kind of view.

Swift
struct Panel: View {
    let isExpanded: Bool

    var body: some View {
        if isExpanded {
            CounterView()   // identity: ".../if-true/CounterView"
        } else {
            CounterView()   // identity: ".../else/CounterView"
        }
    }
}

Each time isExpanded flips, the old CounterView is removed and a brand-new one is inserted, so its @State starts over. If you wanted to keep the counter, write it so it sits in one position and only its inputs change:

Swift
struct Panel: View {
    let isExpanded: Bool

    var body: some View {
        CounterView()
            .frame(height: isExpanded ? 200 : 60)   // same position, same identity
    }
}

The stand-in below models a store of state keyed by identity paths. After each render, state belonging to views that are no longer in the tree is dropped, which is the same rule SwiftUI follows.

Swift State follows identity

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 first and third scenarios reset the count to 0 because the identity path changed; the second keeps 3. A third way to cause the same reset is .id(...), covered below.

Explicit identity

Sometimes position is not enough, especially for collections where items are inserted, removed and reordered. There you provide identity yourself. ForEach uses the id key path (or Identifiable.id) to tell items apart:

Swift
ForEach(todos) { todo in          // Todo: Identifiable, with a stable id
    TodoRow(todo: todo)
}

With stable ids, deleting the first row removes that row's view and state; the others keep theirs, and SwiftUI can animate the removal correctly. If you instead use positions as ids (for example ForEach(0..<todos.count, id: \.self)), deleting row 0 means "row 2 vanished and rows 0 and 1 changed content". Expanded rows and typed text then appear to jump to the wrong item. The rule: an id must identify the item, not its position, and it must not change from one update to the next (a UUID() created inside the body is a classic error, because each update produces new ids).

The id(_:) modifier assigns explicit identity to any view. Changing the value you pass makes SwiftUI treat the view as a different one, discarding its state:

Swift
ScrollView {
    FormView()
        .id(formVersion)   // bump formVersion to reset the form
}

That is a useful tool when you really want a reset, such as clearing a draft after saving. Used by accident (a changing value passed to .id), it causes the "mysterious reset" bug.

Appear, change and disappear

SwiftUI offers modifiers that run code at lifecycle moments of a view with a given identity.

  • onAppear { } runs when the view is inserted into the visible tree. It can run more than once for the same view, for example when a tab is revisited, so make it safe to repeat.
  • onDisappear { } runs when the view is removed from the tree or leaves the screen.
  • task { } starts an asynchronous task when the view appears and cancels it automatically when the view disappears. It is the standard place to load data.
  • task(id: value) { } also restarts the task, cancelling the old one, whenever value changes.
  • onChange(of: value) { oldValue, newValue in } runs when a value changes while the view is on screen. It does not run for the first value, unless you pass initial: true.
Swift
struct ProfileView: View {
    let userID: Int
    @State private var profile: Profile?

    var body: some View {
        content
            .task(id: userID) {            // reload when userID changes
                profile = try? await api.profile(for: userID)
            }
            .onChange(of: userID) { old, new in
                print("switched from \(old) to \(new)")
            }
            .onDisappear {
                // stop work that is not covered by task, e.g. a timer you started
            }
    }
}

Prefer task over onAppear plus a manual Task { }: it ties the work to the view's life, so a user leaving the screen cancels the request instead of leaving it running.

Do not rely on onAppear firing exactly once or on a precise ordering of appear events between sibling views. Treat it as "this view is now visible, possibly again".

Seeing the events

The next stand-in compares two successive renders by identity and prints what SwiftUI would do: disappear and cancel tasks for removed identities, appear and start tasks for new ones, and onChange for identities that stayed but whose watched value differs. It compares a list keyed by stable ids against a list keyed by position when the first item is deleted.

Swift Appear, disappear and change events

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 stable ids, exactly one thing happens: milk goes away. With positions, the last row disappears and two surviving rows report that their content changed, so any state attached to them (text being edited, an expanded section) stays on the wrong item.

Animation and identity

Identity also decides what kind of animation you get. If a view keeps its identity while a property such as its offset or color changes, SwiftUI interpolates the property. If a view gains or loses identity (inserted or removed), SwiftUI applies a transition instead, fading by default.

Swift
if showBanner {
    BannerView()
        .transition(.move(edge: .top))    // runs on insert and removal
}

This explains a common surprise: toggling .id(...) on a view while wrapped in withAnimation produces a transition (old view out, new view in), not a smooth morph, because to SwiftUI they are two different views. Animations are the subject of a later lesson.

Debugging identity problems

When state resets or jumps, check these in order:

  1. Is the view inside an if/else or switch whose branch changes? Move the view out of the branches and vary its inputs.
  2. Is there an .id(...) whose value changes more often than intended?
  3. Does ForEach use positions or UUID() created during rendering as ids? Give the model a stable id.
  4. Is the view wrapped in AnyView? Type erasure hides the structure SwiftUI uses for comparison and can cause extra identity changes (see Common SwiftUI Pitfalls).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the data behind @State live?

    View structs are recreated constantly. SwiftUI keeps state outside them, matched by identity, so the new struct finds the old value.
  2. 2. A CounterView appears in both branches of an if/else. What happens to its state when the condition flips?

    Each branch is a separate structural position. Move the view out of the branches to keep its identity.
  3. 3. Why is ForEach(0..<items.count, id: .self) risky when rows can be deleted?

    An id must identify the item. After deleting row 0, the row at index 0 is now a different item but keeps the same identity.
  4. 4. What does the task modifier do when its view disappears?

    task is tied to the view's lifetime. Use task(id:) to restart when an input value changes.
  5. 5. Which modifier would you use to deliberately reset a form's state after saving?

    Changing the value passed to id(_:) makes SwiftUI treat the view as new, discarding its state. Use it intentionally.

Summary

  • SwiftUI matches new view values to old ones by identity; matched views keep their state, others start fresh.
  • Structural identity comes from position in the tree (each if/else branch is its own position); explicit identity comes from ForEach ids and .id(_:).
  • Use stable, item-based ids, never positions or ids generated during rendering.
  • onAppear can run repeatedly, task cancels with the view, task(id:) restarts on change, and onChange reports changes after the first value.
  • Inserting or removing a view triggers a transition; changing a property of the same view interpolates.

Next, collect the most frequent mistakes from this chapter in Common SwiftUI Pitfalls.