tezvyn:

NavigationStack: Programmatic Navigation in SwiftUI

AI-drafted, machine-checkedSource: developer.apple.comintermediate
NavigationStack: Programmatic Navigation in SwiftUI

Think of NavigationStack as a pile of views. You push new views onto the stack programmatically by appending to a path array. This is SwiftUI's modern, data-driven way to handle deep navigation, replacing the older, buggier `NavigationView`.

WHY IT EXISTS: SwiftUI's original NavigationView was difficult to control programmatically. Developers struggled to push or pop views based on state changes, leading to complex workarounds. NavigationStack was introduced to solve this by providing a robust, data-driven API where the navigation hierarchy is a direct reflection of your app's state.

THE MENTAL MODEL: Think of NavigationStack as a pile of plates, where each plate is a view. You can only add a new plate to the top (pushing a view) or take the top one off (popping a view). The entire pile of plates is represented by a simple array of data you own, called the "path". To change what's on screen, you just modify the array.

HOW IT WORKS: You initialize a NavigationStack with a binding to a path, which is an array of hashable data (e.g., [Int], [String], or custom structs/enums). To push a new view, you use a NavigationLink with a value parameter. When a user taps it, the link's value is appended to your path array. The NavigationStack observes this change and uses a .navigationDestination(for: DataType.self) modifier to find the right view to build for that piece of data. To go back, the system automatically removes the last item from the path. You can also do this programmatically by simply calling path.removeLast().

WHEN TO USE IT: Use NavigationStack for any hierarchical navigation flow, especially those that are more than one level deep. It excels in drill-down interfaces (like a file browser), master-detail patterns, and any scenario where you need to programmatically control the navigation path, such as restoring state or responding to a deep link from a notification.

WHEN NOT TO USE IT: For flat navigation structures, like a main screen with different sections, use TabView. For presenting a single, self-contained view modally (like a compose screen or a login form), use the .sheet() or .fullScreenCover() modifiers. NavigationStack is specifically for managing a stack of related views.

ONE CANONICAL EXAMPLE: An e-commerce app's product browsing flow. The root view is a list of product categories. Tapping "Electronics" pushes a view for that category, and the path might become [Category(id: "electronics")]. Tapping a "Laptops" sub-category pushes another view, and the path becomes [Category(id: "electronics"), Category(id: "laptops")]. The entire user journey is captured in one state variable.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.