TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Navigating to different data types using NavigationPath

Paul Hudson    @twostraws   

Navigating to different data types takes one of two forms. The simplest is when you're using navigationDestination() with different data types but you aren't tracking the exact path that's being shown, because here things are straightforward: just add navigationDestination() multiple times, once for each type of data you want.

For example, we could show five numbers and five strings and navigate to them differently:

NavigationStack {
    List {
        ForEach(0..<5) { i in
            NavigationLink("Select Number: \(i)", value: i)

        ForEach(0..<5) { i in
            NavigationLink("Select String: \(i)", value: String(i))
    .navigationDestination(for: Int.self) { selection in
        Text("You selected the number \(selection)")
    .navigationDestination(for: String.self) { selection in
        Text("You selected the string \(selection)")

However, things are more complicated when you want to add in programmatic navigation, because you need to be able to bind some data to the navigation stack's path. Previously I showed you how to do this with an array of integers, but now we might have integers or strings so we can't use a simple array any more.

SwiftUI's solution is a special type called NavigationPath, which is able to hold a variety of data types in a single path. In practice it works very similarly to an array – we can make a property using it, like this:

@State private var path = NavigationPath()

Bind that to a NavigationStack:

NavigationStack(path: $path) {

Then push things to it programmatically, for example with toolbar buttons:

.toolbar {
    Button("Push 556") {

    Button("Push Hello") {

If you want to feel fancy, NavigationPath is what we call a type-eraser – it stores any kind of Hashable data without exposing exactly what type of data each item is.

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.