In SwiftUI, the first screens are usually wired together with NavigationLink. You tap a list row, a detail opens, and from there you move to a sub-screen. While the app is small this is enough, because navigation is just a handful of small decisions scattered across views.
The problems start when navigation has to be driven from the outside. A notification should take the user to a specific order's detail, a link in an email should open the app on the right screen, the stack should reset when the user signs out, and when the app is reopened the user should see where they left off. If navigation is buried inside views, each of these needs its own patch. In this post I describe modelling navigation as data, gathering it around a single route type and a router object, and translating deep links into that model.
Thinking of navigation as data
The core idea behind NavigationStack is this: the stack on screen is the visual representation of an array. Append an element and a new screen opens, remove the last element and you go back, empty the array and you return to the root. Views do not answer the question "where are we going" themselves; they only change that data.
The practical consequence of this view is defining a single type that represents every destination screen in the app:
enum Route: Hashable, Codable {
case orderList
case orderDetail(id: Order.ID)
case customer(id: Customer.ID)
case settings
}
Hashable is required by NavigationStack. Codable is useful for saving and restoring the stack. Carrying identifiers in routes instead of full model objects is an important decision: the route stays small, it can be encoded, and the destination screen loads its data from the current source itself. Putting an Order object into a route leads to a stale copy staying on screen and makes encoding harder.
NavigationStack and navigationDestination
I bind the stack to an array and define the mapping between routes and screens in one place:
struct OrdersRootView: View {
@State private var path: [Route] = []
var body: some View {
NavigationStack(path: $path) {
OrderListView(onSelect: { order in
path.append(.orderDetail(id: order.id))
})
.navigationDestination(for: Route.self) { route in
destination(for: route)
}
}
}
@ViewBuilder
private func destination(for route: Route) -> some View {
switch route {
case .orderList: OrderListView(onSelect: { path.append(.orderDetail(id: $0.id)) })
case .orderDetail(let id): OrderDetailView(orderID: id)
case .customer(let id): CustomerView(customerID: id)
case .settings: SettingsView()
}
}
}
The navigationDestination modifier should be declared once, at the root of the stack. Declaring it for the same type in several places, or putting it inside a lazily loaded list row, makes it unclear which declaration applies and produces warnings.
Views can also use NavigationLink(value:) here; as long as the value is of the same route type, it is pushed onto the stack. I prefer passing a callback or the router to child views, because that keeps the navigation decision in a place that can be tested.
Managing it with a router object
As long as the stack lives in a single view's @State, it is hard for an external event to reach it. So I move the stack into a small router object:
@MainActor
@Observable
final class Router {
var path: [Route] = []
var sheet: SheetRoute?
func push(_ route: Route) { path.append(route) }
func pop() { if !path.isEmpty { path.removeLast() } }
func popToRoot() { path.removeAll() }
func show(_ routes: [Route]) {
path = routes
}
}
The router is created as @State at the root of the app and placed in the environment. Child views can read it and call push. On sign-out you call popToRoot(), when a notification is tapped you call show(...). The router should do little: change the stack. Loading data, checking permissions or making network requests is the responsibility of the destination screen or its model.
Having show replace the stack in one go is a deliberate choice. For a deep destination, assigning the array at once instead of appending the root, list and detail screens one by one prevents the intermediate screens from animating in individually; the user sees the final screen directly, and the back button still works in the expected order.
Turning deep links into routes
A deep link is really just a URL translated into an array of routes. Writing that translation as a pure function rather than inside a view makes it testable:
struct DeepLinkParser {
func routes(for url: URL) -> [Route]? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
else { return nil }
let parts = components.path.split(separator: "/").map(String.init)
switch parts {
case ["orders"]:
return [.orderList]
case let ["orders", id]:
guard let orderID = UUID(uuidString: id) else { return nil }
return [.orderList, .orderDetail(id: orderID)]
case ["settings"]:
return [.settings]
default:
return nil
}
}
}
The function returns nil for an unknown or malformed URL. In that case it is safer to leave the app where it is, or return to the home screen, than to strand it on some odd intermediate screen. Wiring the link into the app is a single line:
.onOpenURL { url in
if let routes = DeepLinkParser().routes(for: url) {
router.sheet = nil
router.show(routes)
}
}
Every incoming link should be treated as untrusted input. A URL taking a user to someone else's order only becomes a security problem if the destination screen does not check authorization. The router only opens the screen; the decision about access to data is still made on the server and in the destination screen's loading logic. Using the same parser to translate the target information inside push notifications ensures that two different entry points follow the same rules.
Sheets, tabs and multiple stacks
Not every screen belongs on the stack. An edit form, a filter panel or a confirmation screen is usually presented as a sheet. Rather than mixing these with stack routes, I keep them as separate state:
enum SheetRoute: Identifiable {
case editOrder(id: Order.ID)
case newCustomer
var id: String {
switch self {
case .editOrder(let id): "edit-\(id)"
case .newCustomer: "new-customer"
}
}
}
On the view side it is bound with .sheet(item: $router.sheet). When a deep link arrives you must remember to dismiss any open sheet; otherwise the new screen opens behind the sheet and the user sees nothing happen.
In tabbed apps each tab should have its own stack. After drilling three screens deep in the Orders tab, switching to Settings and coming back, the user expects to find the same place. For this I keep the selected tab and a separate route array per tab in the router. The deep link parser then returns not only the route array but also which tab to open it in. TabView(selection:) binds to the selected tab, and the NavigationStack in each tab binds to its own array.
Saving and restoring the stack
When the system terminates the app in the background, the user expects to see the screen they left when they come back. Because routes are Codable, encoding the stack and storing it per scene is not difficult:
@SceneStorage("orders.path") private var savedPath: Data?
.task {
if let savedPath,
let routes = try? JSONDecoder().decode([Route].self, from: savedPath) {
router.path = routes
}
}
.onChange(of: router.path) { _, newPath in
savedPath = try? JSONEncoder().encode(newPath)
}
I pay attention to two things here. First, the encoded data travels across app versions. When you rename or remove a route, old data can no longer be decoded; starting with an empty stack instead of showing an error is the right behaviour. Second, a restored route may point to a record that no longer exists. If the destination screen handles its "not found" state properly, that case resolves itself.
If you use NavigationPath instead of a route array, you can keep different types on the same stack and use its codable property for encoding. In apps with a single route type, a plain array is more readable and easier to test.
Testing navigation
Once navigation is data, tests can be written without UI tests. For the deep link parser I write simple unit tests with input URLs and expected route arrays: valid links, a missing identifier, a malformed identifier, an unknown path. For the router I check behaviours like "does the stack empty on sign-out" and "does the sheet close when a link arrives" directly on the object.
I reserve UI tests for a few critical flows, such as the app cold-starting from a link and reaching the right screen. If the parsing and stack rules are covered by unit tests, UI tests only need to verify that the link actually reaches the view.
Designing navigation not as links scattered across views but as a route type and a small object that manages it looks like a bit of extra structure at first. But once notifications, deep links, session changes and state restoration come into play, this structure lets you solve every new requirement in the same place and with the same rules. Screens focus on what they show, and the router focuses on where the user is.