100 Days of SwiftUI

Day 44

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"]

How to make a NavigationStack return to its root view programmatically

  • too many back buttons? Reset the path to go home > @Binding property wrapper lets us pass an @State property into another view and modify it from there – we can share an @State property 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 NavigationPath object
  • using JSONEncode... etc.
  • since NavigationPath doesn’t need to have Codable objects (only Hashable), 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.