skip to content

In a SwiftUI watchlist, each row conforms to Equatable comparing only its ticker symbol and is wrapped with .equatable(); what can go wrong, and when is that worth doing?

level: seniorimportance: should knowfreq 38%

answer

  1. your == decides what counts as same
  2. true means skip the update
  3. closures capture state too
  4. own dependencies still update

basics

~20 s

With .equatable(), the row's == decides whether a new value from the parent counts as changed. Comparing only the symbol lets a new price or a new action closure be treated as unchanged, so the row can show stale data or run stale actions.

solid answer

~40 s

`.equatable()` wraps the row in `EquatableView`, which Apple documents as preventing the child from updating when its new value is the same as the old, judged by your `==`. If `==` compares only the symbol, a parent passing a new price or a new trade closure gets `true` back, the row's body doesn't run, and the user sees the old price or taps a button bound to the old account. It only gates updates from the parent; the row's own `@State` and observable reads still update it. It's worth it when the body is expensive, the inputs include things like closures recreated every parent run, and `==` covers everything the body uses. Otherwise fix the parent's dependencies, and measure either way.

code

swift · 30 lines
swift
import SwiftUI

struct WatchRow: View, Equatable {
    let symbol: String
    let price: Double
    let onTrade: () -> Void

    // Ignores price and the closure: SwiftUI may treat a
    // changed row as unchanged and keep its old output.
    nonisolated static func == (lhs: WatchRow, rhs: WatchRow) -> Bool {
        lhs.symbol == rhs.symbol
    }

    var body: some View {
        Button("\(symbol) \(price)", action: onTrade)
    }
}

struct Watchlist: View {
    let rows: [(symbol: String, price: Double)]
    let account: String
    var body: some View {
        ForEach(rows, id: \.symbol) { row in
            WatchRow(symbol: row.symbol, price: row.price) {
                print("trade \(row.symbol) for \(account)")
            }
            .equatable()
        }
    }
}

go deeper

for a junior

Recall that .equatable() needs an Equatable view and that its == decides whether a new value counts as a change.

for a middle

Explain that EquatableView gates only parent-driven updates, and that the row's own state and observed reads still update it.

for a senior

Spot an == that skips a displayed field or a captured value, explain the stale price and stale action, and prove the fix with _printChanges.

for a principal

Decide whether a team allows .equatable() at all, and on what evidence, given that it trades a measured speed-up for a class of silent bugs.

## What EquatableView is `EquatableView<Content>` is a SwiftUI view (iOS 13) that wraps a view whose type conforms to both `View` and `Equatable`. You normally create it with the `.equatable()` modifier, which exists only on views that are `Equatable`. Apple's documentation describes it as "a view type that compares itself against its previous value and prevents its child updating if its new value is the same as its old value." The comparison it uses is **your** `==`. So `.equatable()` changes one decision: when a parent re-runs and builds a new row value, your `==` tells SwiftUI whether that value is "the same". Returning `true` means "skip this update". ## The bug: an == that ignores what the row shows A watchlist row has a symbol, a price and an action closure for a trade button. Closures are not `Equatable`, so Swift cannot synthesize `==` for the struct; a developer writes one by hand and compares only the symbol, then adds `.equatable()` to speed up the list. In a test run of exactly that row inside a `ForEach`, two things went wrong: - after a price change, the parent's body ran and `==` was called and returned `true`; the row's body did **not** run, so it kept showing the **old price**; - after switching the account the trade closure captures, the same happened: the button kept the closure from the last body run, which still referred to the **old account**. The second one is worse, because nothing on screen looks wrong. The rule is that `==` must return `false` whenever anything the body uses would differ, including values a closure captured. ## What EquatableView does not block `.equatable()` gates only updates that arrive **from the parent** as a new value. In a test where a row's `==` always returned `true`, a change to an `@Observable` property that the row's **own body** read still re-ran the row. Its own `@State` and the environment values it reads behave the same way. It is not a freeze. ## When it is worth it | Situation | Use .equatable()? | |---|---| | Expensive body, inputs include a closure recreated on every parent run, `==` can cover what matters | yes, carefully | | Body is cheap | no, the comparison buys nothing | | You can make the parent stop re-running instead | no, fix the dependency upstream | | `==` would have to skip a displayed field to be "fast" | no, that is the stale-row bug | SwiftUI also compares view values itself, and it does not document when it consults your `==`; in some layouts a changed stored value updated the view without `==` being called. So `.equatable()` is an optimization you **measure**, not a correctness tool and not a guaranteed skip. ## Alternatives that avoid the risk Before reaching for `.equatable()`, try to make the row's inputs **honest and stable**: - pass the plain values the action needs (the symbol, an account identifier) and let the row call a shared action with them, instead of storing a closure that captures parent state; - stop the parent from re-running on every tick, by moving the read of the changing value into the rows; - if the row needs live data, hand it the `@Observable` object and let its body read the property, so updates arrive through its own dependencies. When those leave nothing to gain, `.equatable()` has nothing left to do. ## A checklist for a pull request that adds .equatable() 1. List every stored property and every value a stored closure captures. 2. Confirm `==` compares each one that affects what the body draws or does, or document why one cannot change. 3. Add `let _ = Self._printChanges()` temporarily, change each input once, and confirm the row updates. 4. Compare body counts in the SwiftUI template in Instruments before and after; if the count barely moves, delete the conformance. 5. In Swift 6 language mode, a `static func ==` inside a `View` struct is main-actor isolated like the rest of the type, and the `Equatable` conformance fails to compile; marking the operator `nonisolated` fixes it when it only reads `Sendable` stored values. The broader lesson: narrowing dependencies (smaller views, reads where values are displayed) is the default fix for redraw cost; `EquatableView` is a targeted tool for the case where a parent cannot avoid handing a child new but meaningless values.

  • Does .equatable() stop a row from updating when its own @Observable data changes?
    No. It gates new values arriving from the parent. If the row's own body read an observable property, or the row's own `@State` changes, the row still re-runs. In a test with `==` always returning `true`, a price the row read itself still updated it.
  • Why does a hand-written == often appear on rows in the first place?
    Because a row that stores a closure cannot get a synthesized `Equatable` conformance; closures are not `Equatable`. Developers write `==` by hand and are tempted to compare only an identifier, which is where the stale-row bug comes from.

A receptionist who checks only the name on a visitor's badge: fast, until the same name arrives with a new role and is waved through on the old one. The check is only as safe as the fields it looks at.

  • comparing the id in == is enough to keep rows correct
  • .equatable() freezes a row until its identity changes
  • EquatableView makes List rows lazy
  • closures in a view are irrelevant to its equality
  • .equatable() is a guaranteed body skip whenever == returns true