< Programmatic navigation with NavigationStack | How to make a NavigationStack return to its root view programmatically > |
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") {
path.append(556)
}
Button("Push Hello") {
path.append("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.
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.