100 Days of SwiftUI
2026-06-02
Project 9, part 2
How to handle programmatic navigation, but also how to load and save navigation paths so you can restore your app’s state
Programmatic navigation with NavigationStack
- “programmatic navigation” to switch views based solely on code, not on the user doing something in particular
- bind a path variable to the
NavigationStack(as an array) - call the path in code, including any subpaths
- use the modifier
navigationDestination()
You can put the view in the initiator (in this example, a button) and it doesn’t need to be added to the array before using it. I imagine you create the array so you can save state later.
I tried to replace the Int array with a String array but wasn’t entirely successful in doing it without typing the strings in e.g. path = ["string 1", "string 2"]
Navigating to different data types using NavigationPath
- this is for mixed-types of navigation views
- you don’t need the array unless you intend to keep the path(s)
- since you might have, say,
Strings andInts in your path, you need to use a special SwiftUI type calledNavigationPath NavigationPathuses “type erasure” which means it will store different types of items as long as they areHashable- I wonder what
Representation.eagermeans? (It’s internal. It has a.lazycounterpart)
You selected the string Hello
Path = NavigationPath_items:
SwiftUl.NavigationPath.(unknown context at $1d36ffa00).Representation.eager([CodableltemBox (Hello)]), subsequentitems: [l, iterationindex: O)
- unlike the standard array used in the first example (where you could just say
path = [56]), you can’t easily talk to theNavigationPath()object.
Cannot assign value of type ‘String’ to type ‘NavigationPath’
How to make a NavigationStack return to its root view programmatically
- too many back buttons? Reset the path to go home >
@Bindingproperty wrapper lets us pass an@Stateproperty into another view and modify it from there – we can share an@Stateproperty in several places, and changing it in one place will change it everywhere.
How to save NavigationStack paths using Codable
- can be done with either the array-style path object or the
NavigationPathobject - using
JSONEncode...etc. - since
NavigationPathdoesn’t need to haveCodableobjects (onlyHashable), need to check that you can decode it first.
This is all very theoretical. I can understand why you would be doing this, but the “sandbox” code he’s using to demonstrate it doesn’t really help me understand how I would use it in an app.