skip to content

With SwiftUI's NavigationStack, when do you bind a typed array versus a NavigationPath, and how do you push, pop and pop to root?

level: middleimportance: must knowfreq 68%

answer

  1. one route type or many
  2. type erasure hides the elements
  3. append and removeLast
  4. no removeAll on NavigationPath

basics

~20 s

Bind a typed array when every pushed value shares one route type, so code can read it; bind a NavigationPath when one stack mixes types. Push with append, pop with removeLast, and pop to root by emptying the path.

solid answer

~40 s

`NavigationStack(path:root:)` accepts either a binding to a collection of `Hashable` values, typically `[Route]`, or a binding to `NavigationPath`. The stack keeps the binding in sync: it appends when a value link is tapped and removes when the user goes back. A typed array is the right choice when one enum covers every screen: you can read its elements, check what is on top, and assign a whole new array to rebuild the stack. `NavigationPath` is type-erased, so it holds different route types in one stack, but it only exposes `count`, `isEmpty`, `append(_:)`, `removeLast(_:)` and `codable`. Push with `append`; pop with `removeLast()`; pop to root with `removeAll()` on an array, or `removeLast(path.count)` or a fresh `NavigationPath()` on a path. Inside a pushed screen, `@Environment(\.dismiss)` pops just that screen.

code

swift · 30 lines
swift
enum OrderRoute: Hashable {
    case order(id: String)
    case shipment(orderID: String)
}

struct OrdersTab: View {
    @State private var path: [OrderRoute] = []

    var body: some View {
        NavigationStack(path: $path) {
            List {
                Button("Order A1") { path.append(.order(id: "A1")) }
                Button("Track A1") {
                    path = [.order(id: "A1"), .shipment(orderID: "A1")]
                }
            }
            .navigationDestination(for: OrderRoute.self) { route in
                switch route {
                case .order(let id):
                    OrderDetailView(orderID: id)
                case .shipment(let id):
                    ShipmentView(orderID: id)
                        .toolbar {
                            Button("Done") { path.removeAll() } // pop to root
                        }
                }
            }
        }
    }
}

go deeper

for a junior

Recall that NavigationStack(path:) takes a binding, that append pushes and removeLast pops, and that emptying the path returns to the root view.

for a middle

Explain the two initializers, why NavigationPath can mix types yet cannot be read, and the different pop-to-root calls each type needs.

for a senior

Justify the choice by what the router must do: inspect the top screen, trim stale entries, compare in tests, or mix feature route types.

for a principal

Treat the path type as an architecture decision: one app-wide enum keeps stacks inspectable but couples features, while NavigationPath decouples them at the cost of visibility.

## What the path is A `NavigationStack` (iOS 16 and later) can manage its own navigation state, but you can **share control** by passing a binding through `init(path:root:)`. The binding holds one data value for each pushed screen, in order; the root view is not in it. SwiftUI keeps the two in sync in both directions: - when someone taps a `NavigationLink(value:)`, the stack appends the value; - when someone taps Back or swipes, the stack removes the last value; - when your code changes the collection, the stack changes what it shows. Apple's documentation describes this with a `showParks()` method that assigns two parks at once: the stack shows the second park's detail, and navigating back reveals the first. Assigning the whole collection is therefore how you build a multi-level stack in one step. ## Two kinds of path The SDK declares two path initializers. One takes `Binding<NavigationPath>`; the other takes `Binding<Data>` where `Data` is a `MutableCollection`, `RandomAccessCollection` and `RangeReplaceableCollection` of `Hashable` elements, which in practice means an array. | | Typed array, e.g. `[OrderRoute]` | `NavigationPath` | |---|---|---| | Element types | one | any mix of `Hashable` types | | Read the elements | yes: `last`, subscripts, `contains`, iteration | no: only `count` and `isEmpty` | | Push | `append(_:)` | `append(_:)` | | Pop one | `removeLast()` or `popLast()` | `removeLast()` | | Pop to root | `removeAll()` or assign `[]` | `removeLast(path.count)` or assign `NavigationPath()` | | Persist | encode the array if the element is `Codable` | `codable` gives a `CodableRepresentation`, or `nil` | | Compare for changes | `Equatable` when the element is | `Equatable` | **`NavigationPath` is type-erased.** Apple describes it as "a type-erased list of data", and recommends an array for homogeneous data. The erasure is the price of heterogeneity: you cannot ask a `NavigationPath` which route is on top, because it declares no subscript or `last`. ## Choosing between them Prefer a **typed array** when a single enum describes every screen the stack can show: 1. It is inspectable. A router can check `path.last` before pushing a duplicate, or trim the path after an item is deleted. 2. It is easy to test. Two arrays of an `Equatable` enum compare directly. 3. Assigning a literal array, such as `[.order(id: "A1"), .shipment(orderID: "A1")]`, reads like the screen stack it builds. Prefer **`NavigationPath`** when one stack must show values of unrelated types that you don't want to fold into one enum, typically routes contributed by separate feature modules. You lose inspection; you keep one stack. ## Push, pop and pop to root - **Push**: `path.append(value)`. On a `NavigationPath` you can append any `Hashable` value; the SDK has a second overload for values that are also `Codable`. - **Pop one**: `path.removeLast()`. Both types support `removeLast(_ k:)` with a count. On an array, removing more elements than it holds is a runtime precondition failure, so guard with `count`. - **Pop to root**: an array has `removeAll()`; `NavigationPath` has no `removeAll`, so write `path.removeLast(path.count)` or assign `NavigationPath()`. The root view itself can never be removed; Apple notes that the stack disables Back when the path is empty. - **Pop from inside a screen**: `@Environment(\.dismiss)` gives a `DismissAction`, and Apple's documentation lists popping the current view from a `NavigationStack` as one of its uses. It is handy for a screen that should not know the path exists. ## Observing what the user did Because the stack writes the binding, back gestures show up as ordinary state changes. Observe them with `onChange(of:initial:_:)` (the two-value form added in iOS 17; the one-parameter `onChange(of:perform:)` is deprecated), or with `didSet` on a property of an `@Observable` router, which is what Apple's own path examples use. ## Common mistakes - Choosing `NavigationPath` by default, then needing to know which screen is on top. - Calling `removeAll()` on a `NavigationPath`, which declares no such method. - Keeping one `@State` Boolean per screen instead of one path, which is the pattern the deprecated `isActive` links forced. - Removing more values than the path holds.

  • In SwiftUI, how does code learn that the user popped a screen with the Back button or a swipe?
    The stack removes the value from the bound collection, so the pop arrives as an ordinary state change. Observe it with `onChange(of:initial:_:)` on the path (iOS 17's two-value form), or with `didSet` on a stored `path` property of an `@Observable` router, as Apple's examples do. There is no separate pop callback to register.
  • Why not keep one Boolean @State per screen and push with navigationDestination(isPresented:) everywhere?
    Booleans describe one screen each, so a three-level stack needs three flags that must stay consistent, and nothing records their order. A path is a single ordered value: one assignment builds or clears the whole stack, and it can be saved and restored. Apple's documentation recommends binding a path for programmatic navigation and keeps `isPresented:` for a one-off push.

A bound path is a stack of index cards on your desk that the app mirrors: add a card and a screen slides in, take one off and it slides out. A typed array is a stack of one kind of card you can read; a NavigationPath is a sealed box of mixed cards you can only count, add to and take from the top.

  • Use NavigationPath everywhere, it is strictly better than an array
  • Call removeAll() on a NavigationPath to return to the root
  • Read path.last on a NavigationPath to see the top screen
  • NavigationPath can only hold one route type
  • The root view is the first element of the path