skip to content

In a SwiftUI code review, a helper returns AnyView for each weather card variant; what does that erasure cost, and when is AnyView acceptable?

level: seniorimportance: should knowfreq 45%

answer

  1. type erasure hides the concrete type
  2. a type change rebuilds the subtree
  3. state inside resets on a swap
  4. builder switch or generics first

basics

~20 s

AnyView hides the concrete view type, and when the wrapped type changes SwiftUI destroys the old hierarchy and builds a new one, resetting its state. Prefer a @ViewBuilder switch or generics; keep AnyView for genuinely open-ended view types.

solid answer

~50 s

`AnyView` is a type-erased view: its static type no longer says which view is inside. Apple documents the main consequence — whenever the type wrapped by an `AnyView` changes, the old hierarchy is destroyed and a new one is created for the new type, so `@State` inside resets and the new subtree appears afresh. Apple's documentation for `DebugReplaceableView` (iOS 26 and later), which SwiftUI uses to type-erase debug builds much like `AnyView`, also notes that erasure can impact performance, especially with dynamic content such as `ForEach` or `List`. So in review I'd replace `func card(for:) -> AnyView` with a `@ViewBuilder` function returning `some View` that switches over the kind, keeping every card's type. `AnyView` stays acceptable where view types are genuinely open-ended — views registered at runtime, or a non-generic type that must store an arbitrary view — and where each instance always wraps the same type.

code

swift · 32 lines
swift
import SwiftUI

enum CardKind {
    case temperature(Int)
    case wind(speed: Int)
    case alert(String)
}

// Before: every card is erased, and the type swaps when kind changes
func erasedCard(for kind: CardKind) -> AnyView {
    switch kind {
    case .temperature(let celsius):
        return AnyView(Text("\(celsius)°"))
    case .wind(let speed):
        return AnyView(Label("\(speed) km/h", systemImage: "wind"))
    case .alert(let message):
        return AnyView(Text(message).foregroundStyle(.red))
    }
}

// After: one conditional type that names every card
@ViewBuilder
func card(for kind: CardKind) -> some View {
    switch kind {
    case .temperature(let celsius):
        Text("\(celsius)°")
    case .wind(let speed):
        Label("\(speed) km/h", systemImage: "wind")
    case .alert(let message):
        Text(message).foregroundStyle(.red)
    }
}

go deeper

for a junior

Recall that AnyView wraps any view and hides its type, and that a @ViewBuilder function returning some View is the usual way to return different views without it.

for a middle

Explain the documented behaviour: a change of the wrapped type destroys and recreates the hierarchy, so state inside resets, and name the builder and generic alternatives.

for a senior

Diagnose and review: spot AnyView that swaps types per enum case, rewrite it as a builder switch, keep it where types are open-ended, and measure list performance in release builds.

for a principal

Treat erasure as a codebase convention: when an open-ended registry of views justifies AnyView, and how a team keeps erasure out of hot paths without banning it outright.

## What AnyView is `AnyView` is SwiftUI's **type-erased view**: a `@frozen struct` that conforms to `View` and wraps any other view. You create one with `AnyView(someView)` or the equivalent `AnyView(erasing: someView)`, which simply calls the first initializer. Its `Body` type is `Never`: like SwiftUI's other primitive views it has no `body` of its own. After wrapping, the static type is just `AnyView`; nothing in the type says whether a `Text`, a `Label` or a whole subtree is inside. That is exactly why people reach for it. A function with several `return` statements of different view types does not compile with a `some View` return, and wrapping each in `AnyView` makes the error go away. The question in a code review is what that convenience costs. ## The documented cost: a type change rebuilds the hierarchy Apple's documentation states the key behaviour: **whenever the type of view used with an `AnyView` changes, the old hierarchy is destroyed and a new hierarchy is created for the new type.** In practice: - **State inside resets.** Any `@State` in the old subtree belongs to a hierarchy that no longer exists, so the new one starts from its initial values. - **Appearance can run again.** To SwiftUI the new subtree is a newly created hierarchy, so its appearance handlers can fire again. - **The static type tells nothing.** A `@ViewBuilder` conditional records every possible branch in its type; an `AnyView` only records that *some* view is there. How SwiftUI decides that two descriptions are "the same view" — and why a changed identity resets state in general — is the subject of the lesson on view identity and lifetime. The AnyView-specific fact is the documented rebuild on a type change. ## Performance, and how to measure it Apple's documentation for `DebugReplaceableView`, a type available from iOS 26, adds a second data point. In debug builds SwiftUI erases opaque result types to `DebugReplaceableView` so that Xcode Previews can swap a view's definition without a full rebuild, and the documentation notes that this type erasure, which works much like `AnyView`, **can impact performance, especially with dynamic content such as `ForEach` or `List`**, so performance testing should be done in release mode. Two lessons follow: 1. Erasure is a plausible cost in long, dynamic collections; treat `AnyView` inside a `ForEach` row as something to justify. 2. Measure in a release build before and after removing erasure. How to profile redraws is covered with SwiftUI performance. ## Replacing AnyView | Approach | Concrete type kept? | Typical use | |---|---|---| | `@ViewBuilder` function with `switch` | Yes, a conditional type | Different views per enum case | | Generic parameter `<Content: View>` | Yes, chosen by the caller | Containers that wrap caller content | | `Group` around a conditional | Yes | One modifier for every branch | | `AnyView` | No | View types that are genuinely open-ended | The usual refactor is the first row: mark the function `@ViewBuilder`, return `some View`, remove the `return` statements and `switch` over the kind. Each case keeps its type, and the function's result is one conditional type. Generic container views are covered with reusable components. ## When AnyView is still acceptable - **Open-ended view types.** A registry where views are supplied at runtime, such as cards registered by feature modules, cannot be expressed as one conditional type. - **Storage in a non-generic type.** A property that must hold an arbitrary view inside a type you cannot make generic. - **A stable wrapped type.** If each `AnyView` instance always wraps the same type, the documented rebuild on a type change never fires. - **One erased view outside any collection.** A single `AnyView` whose wrapped type never changes carries little risk, though the builder is still preferable when it costs nothing. - **SwiftUI's own use.** `ViewBuilder` wraps `if #available` branches in `AnyView` through `buildLimitedAvailability`; that erasure is deliberate and fine. ## The review comment A good review comment names the concrete risk rather than a rule: "this `AnyView` swaps types when the card kind changes, so state inside the card resets; a `@ViewBuilder` `switch` keeps the types and the code is no longer." That shows you know what is documented, what is plausible and how you would check it.

  • Is returning any View a better replacement for AnyView in a SwiftUI helper?
    No. An `any View` existential does not itself conform to `View`, so it cannot serve as `body` or as a container's content without being wrapped in `AnyView` again. The replacement that keeps types is a `@ViewBuilder` function returning `some View`; the language-level difference between `some` and `any` is covered with Swift's opaque and existential types.
  • If an AnyView in a list row always wraps the same view type, is it still a problem?
    The documented rebuild only happens when the wrapped type changes, so a stable type avoids the state reset. Apple's notes on debug-build erasure still say type erasure can cost performance with dynamic content like `ForEach` or `List`, so the honest answer is to measure in a release build; if removing the erasure is easy, remove it.

  • AnyView is free; SwiftUI sees through it to the concrete type.
  • When an AnyView's wrapped type changes, SwiftUI updates the old views in place.
  • AnyView(erasing:) keeps the concrete type, unlike AnyView(_:).
  • Returning any View is the type-preserving alternative to AnyView.
  • Performance of type-erased lists can be judged reliably from a debug build.

AnyView's documented rebuild on a type change holds since iOS 13; the DebugReplaceableView note on debug-build erasure applies from iOS 26.