Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 46 ยท Navigation and App Structure

NavigationStack and Navigation Paths

Learn SwiftUI NavigationStack: value-based NavigationLink, navigationDestination, path bindings and programmatic navigation, with a runnable path-stack model.

Most apps have screens that lead to other screens: a list leads to a detail, a detail leads to an edit form, and a back button returns you. On iOS this is a navigation stack: screens are pushed on top of each other, and the system gives you the title bar, the back button and the swipe-from-the-edge gesture to pop.

SwiftUI's NavigationStack represents that stack as data. The stack is simply a list of values, one per pushed screen, and each value is turned into a screen by a destination you declare. Because the stack is data, you can inspect it, add to it, remove from it, save it and restore it, which makes deep links and "go back to the start" trivial. This lesson shows the pieces and then models the idea in plain Swift. SwiftUI code itself is read-only here. It builds on state and bindings and lists.

Navigation is data

The stack An array of values, one per screen.
Links Push a value onto the stack.
Destinations Turn each value into a screen.

Change the array and the screens change.

1 / 2

The basic pieces

A minimal stack with value-based links looks like this:

Swift
struct Book: Identifiable, Hashable {
    let id: Int
    let title: String
}

struct LibraryView: View {
    let books = [Book(id: 1, title: "Swift Basics"), Book(id: 2, title: "Layout Notes")]

    var body: some View {
        NavigationStack {
            List(books) { book in
                NavigationLink(book.title, value: book)      // pushes a Book value
            }
            .navigationTitle("Library")
            .navigationDestination(for: Book.self) { book in // builds the screen for a Book
                BookDetail(book: book)
            }
        }
    }
}

Three things cooperate:

  • NavigationStack owns the stack and shows its top screen. The first view (the root) is always at the bottom.
  • NavigationLink(_:value:) does not name a screen. It says "push this value", and the value must be Hashable.
  • navigationDestination(for:destination:) says "whenever a value of this type is pushed, show this view". It is registered once for a type, so many links can share it.

Splitting the what (a value) from the how (a destination view) is the key design. Links stay tiny, and every screen is created in one place.

Older code uses NavigationView and NavigationLink(destination:). NavigationView is deprecated; use NavigationStack for single-column navigation and NavigationSplitView for sidebars (see the iPad lesson).

Declare navigationDestination on a view that is always present inside the stack (the root content or the list container), not on each row inside a lazy container. Rows can be created and removed as you scroll, and a destination attached to them might not be registered when you need it.

Owning the path

If you want to control the stack, give it a path binding. The path is state owned by you, so it is a @State (or a property of an observable model).

Swift
enum Route: Hashable {
    case book(Book)
    case author(String)
    case settings
}

struct AppView: View {
    @State private var path: [Route] = []

    var body: some View {
        NavigationStack(path: $path) {
            HomeView()
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .book(let book): BookDetail(book: book)
                    case .author(let name): AuthorView(name: name)
                    case .settings: SettingsView()
                    }
                }
        }
    }
}

A typed array ([Route]) works when every screen is described by one enum, which is easy to read and test. When the stack must hold values of several unrelated types, use the type-erased NavigationPath: @State private var path = NavigationPath(). It offers append(_:), removeLast(_:) and count, and it can produce a Codable representation to save and restore the stack.

Now navigation is just array manipulation:

Swift
path.append(.settings)             // push a screen
path.removeLast()                  // pop one screen (same as the back button)
path.removeAll()                   // pop to the root
path = [.book(book), .author("Ada")]   // jump to a deep screen with a back stack

A child view can also pop itself with the dismiss environment action, which removes its own screen from the stack. That works without knowing the path at all.

A navigation stack you can run

SwiftUI cannot run on the site, but the model underneath is plain Swift: an array of hashable routes plus a function from route to screen. The stand-in below implements that and prints the visible screen and the back stack after each operation.

Swift A path-based navigation model

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.

Notice that "deep link to settings" needs no animation code and no screen instances: replacing the array is enough. In SwiftUI, assigning path = [.book(book), .settings] makes the stack show Settings with the book screen underneath, and the back button leads there.

Type-erased paths and destinations by type

With NavigationPath, the stack can mix types, and each destination is chosen by the pushed value's type. The stand-in below mimics that with [AnyHashable] and a registry of handlers keyed by type, including what happens when no destination is registered.

Swift Choosing a destination by value type

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 Double has no destination. In SwiftUI the equivalent mistake pushes a value for which no navigationDestination exists: the link does nothing visible, and a runtime message in the console tells you the destination is missing. Check that every pushed type has a registered destination.

Titles, toolbars and the back button

Each screen sets its own bar content:

Swift
BookDetail(book: book)
    .navigationTitle(book.title)
    .navigationBarTitleDisplayMode(.inline)
    .toolbar {
        ToolbarItem(placement: .primaryAction) {
            Button("Share", systemImage: "square.and.arrow.up") { /* ... */ }
        }
    }

The system adds the back button, labeled with the previous screen's title. You can hide it with navigationBarBackButtonHidden(true) for flows such as checkout, but then you are responsible for offering another way out.

Design tips

  • Prefer an enum Route for apps with a handful of screens; it makes navigation exhaustive and testable.
  • Keep the path in an observable model if non-view code (a deep link handler, a notification) needs to navigate. See Deep Links and Universal Links.
  • Store only identifiers or small values in routes (.book(id: 1)) when possible, and look the full model up in the destination. That avoids stale copies when the data changes.
  • Never nest one NavigationStack inside another stack's screen; you get two bars and confusing back behavior. Each tab, however, typically has its own stack (next lesson).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In value-based navigation, what does NavigationLink("Open", value: book) do?

    Links push values. The destination registered for the value's type builds the screen.
  2. 2. Which type must pushed values conform to for a typed path?

    The stack needs to compare and store values, so they must be Hashable.
  3. 3. How do you pop to the root screen from code when you own the path?

    The stack is data. An empty path shows only the root view.
  4. 4. When would you choose NavigationPath over a [Route] array?

    NavigationPath is type-erased. A typed array is simpler and more readable when one enum describes every screen.
  5. 5. Where should navigationDestination be attached?

    Destinations on views that are created and removed lazily may not be registered when needed.

Summary

  • NavigationStack shows the top of a stack of values; the root is always at the bottom.
  • NavigationLink(value:) pushes a Hashable value and navigationDestination(for:) maps a type to a screen.
  • Bind the stack to a path you own ([Route] or NavigationPath) to push, pop, reset and deep-link with plain array operations.
  • Keep routes small, register a destination for every pushed type, and avoid nesting stacks.

Next: Tab Views, Sheets, Alerts and Popovers.