In SwiftUI, why switch a container between HStackLayout and VStackLayout through AnyLayout rather than an if-else choosing HStack or VStack?
answer
- same container, new arrangement
- structural identity survives
- type-erased Layout
- children keep their @State
basics
~20 sAnyLayout type-erases a Layout, so one container keeps its identity while its arrangement changes: children keep their @State and animate to new positions, whereas an if-else between HStack and VStack destroys one subtree and builds another.
solid answer
~40 s`HStack` and `VStack` are different view types, so an `if-else` between them creates two branches with different structural identity: flipping the condition removes one subtree and inserts the other, the children's `@State` starts over, and any animation plays as a removal and an insertion. `HStackLayout`, `VStackLayout`, `ZStackLayout` and `GridLayout` are the same containers as `Layout` conformers, and `AnyLayout` (iOS 16) erases their type so one expression, `let layout = compact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())`, drives a single container. Apple's docs say it changes the layout type "without destroying the state of the subviews", so with `withAnimation` or `animation(_:value:)` the children move to their new places. It works with custom layouts too, such as collapsing a radial menu into a row.
code
swift · 31 linesimport SwiftUI
struct FilterBar: View {
@State private var isVertical = false
var body: some View {
let layout = isVertical
? AnyLayout(VStackLayout(alignment: .leading))
: AnyLayout(HStackLayout())
VStack {
layout {
FilterChip(title: "Open now")
FilterChip(title: "Under $20")
FilterChip(title: "4 stars and up")
}
Button("Switch arrangement") {
withAnimation { isVertical.toggle() }
}
}
}
}
struct FilterChip: View {
let title: String
@State private var isOn = false
var body: some View {
Toggle(title, isOn: $isOn).toggleStyle(.button)
}
}go deeper
Remember that HStackLayout and VStackLayout are layout versions of the stacks, and AnyLayout lets one container switch between them.
Explain why an if-else gives two identities that reset child state, and how AnyLayout keeps a single container whose arrangement changes.
Show you choose the layout value first and call it once, animate with withAnimation or animation(_:value:), and keep child identities stable.
Decide where adaptive switches live in shared components, and when switching with AnyLayout suits better than measuring alternatives with ViewThatFits.
## The problem with switching stacks A common adaptive requirement: show a set of controls side by side normally and stack them when space or text size demands it. The obvious code is an `if` that returns an `HStack` in one branch and a `VStack` in the other. It compiles and looks right in a static screenshot, but SwiftUI sees **two different views**. Views in different branches of an `if` have different **structural identity**, and here the containers are different types as well, so when the condition flips SwiftUI removes the old subtree and creates a new one. Two consequences follow: - any `@State` inside the children (a toggle's value, a text field's draft, an expanded section) starts over at its initial value; - an animation, if one is active, plays as the old stack leaving and the new one arriving, not as views sliding to new positions. Wrapping each branch in `AnyView` does not help. Apple's documentation for `AnyView` says that whenever the wrapped view's type changes, "the old hierarchy is destroyed and a new hierarchy is created for the new type." ## What AnyLayout changes `AnyLayout`, added in iOS 16, is a **type-erased `Layout`**. Its initializer, `AnyLayout(_:)`, accepts any value that conforms to the `Layout` protocol, and the result is itself a `Layout`, so you call it like a container: `layout { … }`. Both branches of the choice now produce the same type, so the container and its children keep one identity; only the arrangement algorithm inside changes. Apple's documentation states the purpose directly: `AnyLayout` enables "dynamically changing the type of a layout container without destroying the state of the subviews." The layout value is cheap to build: `HStackLayout()` is a small struct holding an alignment and an optional spacing, so creating it in `body` on every evaluation is the normal pattern, exactly as Apple's own example does with a `let layout = …` line before the container. ## The layout versions of the built-in containers The built-in stacks are views, not layouts, so SwiftUI ships `Layout`-conforming twins for use with `AnyLayout`: | Container view | Layout type | Parameters | |---|---|---| | `HStack` | `HStackLayout` | `alignment:` (vertical), `spacing:` | | `VStack` | `VStackLayout` | `alignment:` (horizontal), `spacing:` | | `ZStack` | `ZStackLayout` | `alignment:` | | `Grid` | `GridLayout` | `alignment:`, `horizontalSpacing:`, `verticalSpacing:` | | your own container | any `Layout` conformer | whatever you define | Apple's guidance on `HStackLayout` is to use plain `HStack` when you don't need a conditional layout; the layout types exist for exactly this switch. Lazy stacks have no layout twin, so they cannot be wrapped. ## Animating the switch Because identity is preserved, an ordinary animation moves each child from its old frame to its new one: 1. Derive the choice from state or an environment value, such as a toggle or `dynamicTypeSize`. 2. Build `AnyLayout(HStackLayout())` or `AnyLayout(VStackLayout())` from that value, in one expression. 3. Change the value inside `withAnimation`, or attach `animation(_:value:)` to the container keyed on the value. Apple's "Composing custom layouts with SwiftUI" sample does this with a custom radial layout: when three pets tie, it swaps `AnyLayout(MyRadialLayout())` for `AnyLayout(HStackLayout())`, and "because the structural identity of the views remains the same throughout, the `animation(_:value:)` view modifier creates animated transitions between layout types." The same technique covers your own containers: because `AnyLayout(_:)` takes any `Layout`, a radial menu can collapse into a row, or a flow of chips can become a single column, with every child animating between the two. ## Pitfalls - **Rebuilding the children per branch.** Calling `VStackLayout() { content }` in one `if` branch and `HStackLayout() { content }` in the other reintroduces the identity break; choose the layout value first, then call it once. - **Reaching for `transition(_:)`.** Transitions animate insertion and removal; nothing is inserted here, so the movement comes from the layout change itself. - **Confusing it with `ViewThatFits`**, which measures alternatives and shows the first one that fits; that tool belongs to grids and adaptive arrangement. - **Using the value-less `animation(_:)`.** It has been deprecated since iOS 15; use `animation(_:value:)` or `withAnimation` instead. - **Unstable child identity inside.** `AnyLayout` preserves the container's identity, not that of children produced by a `ForEach` with unstable IDs.
- Can AnyLayout switch between a custom layout and a built-in one?Yes. `AnyLayout(_:)` accepts any type that conforms to `Layout`, including your own. Apple's custom-layout sample swaps its radial layout for `HStackLayout` when three entries tie, and because the avatars keep their identity, `animation(_:value:)` moves them from the circle into a row.
- Does AnyLayout protect child state when the children themselves change?No, it only preserves identity across the layout switch. Children inside the closure still follow the normal identity rules: a `ForEach` keyed on stable IDs keeps each child's state, while children keyed on unstable values, or placed in their own `if` branches, can still reset.
Rearranging the furniture in one room rather than moving into a different room: the chairs are the same chairs, the coat stays on the back of one, and you can watch them slide into their new places.
- An if-else between HStack and VStack keeps child @State because the child code is identical.
- Wrapping each branch in AnyView preserves state across the switch.
- AnyLayout can wrap a LazyVStack for long content.
- Switching layouts needs matchedGeometryEffect on every child to animate.
- AnyLayout requires iOS 17 or later.