skip to content

How do you restore a SwiftUI NavigationStack's path after relaunch, and why can NavigationPath's codable property return nil?

level: seniorimportance: should knowfreq 42%

answer

  1. save identifiers, not screens
  2. Codable routes in the path
  3. CodableRepresentation round trip
  4. one non-Codable element spoils it

basics

~20 s

Make every route value Codable, encode the path when the scene goes to the background, and decode it at launch. NavigationPath's codable returns nil when any element in the path isn't Codable, because the path itself only requires Hashable.

solid answer

~40 s

A bound path is plain data, so restoring a `NavigationStack` means persisting that data. With a typed array of a `Codable` route enum, I encode the array directly. With a `NavigationPath`, I read `path.codable`, which returns a `NavigationPath.CodableRepresentation`, encode it with `JSONEncoder`, and later rebuild with `NavigationPath(_:)` from the decoded representation. `codable` is optional because `NavigationPath` only requires `Hashable` elements; Apple's guide says it returns `nil` if any element doesn't conform to `Codable`, which the compiler can't check. I save when `scenePhase` becomes `.background`, store it per scene with `@SceneStorage` as `Data`, keep routes as IDs so screens reload current data, fall back to an empty path when decoding fails after an update, and let a deep link override the restored stack.

code

swift · 17 lines
swift
@Observable @MainActor
final class OrdersRouter {
    var path = NavigationPath()

    func encodedPath() -> Data? {
        guard let representation = path.codable else { return nil } // a non-Codable element
        return try? JSONEncoder().encode(representation)
    }

    func restore(from data: Data) {
        guard path.isEmpty, // a deep link that already built a stack wins
              let representation = try? JSONDecoder().decode(
                  NavigationPath.CodableRepresentation.self, from: data)
        else { return } // undecodable after an update: stay at the root
        path = NavigationPath(representation)
    }
}

go deeper

for a junior

Recall that the bound path is just data: if the route values are Codable you can save them and set them back at launch.

for a middle

Explain the CodableRepresentation round trip, why codable is optional, and how a typed Codable array moves that check to compile time.

for a senior

Show the production details: save on background, per-scene storage, IDs instead of models, a reset on decoding failure, deleted items, and links that beat restoration.

for a principal

Decide which flows deserve restoration at all, and set the rule that every route type stays Codable and versionable as features evolve.

## Why restoration is a data problem A `NavigationStack` bound to a path shows the screens its path lists. If the path survives a relaunch, the stack does too. Restoration therefore has three steps: make the path **encodable**, **save** it at the right moment, and **load** it into the binding before the user starts navigating. Apple's guide on the navigation stack frames it the same way: restore the path as you would restore other scene-level state. ## Making the path encodable There are two cases, matching the two path types `NavigationStack(path:root:)` accepts: - **Typed array.** If the route enum is `Codable`, `[Route]` is `Codable` too. Encode and decode it directly with `JSONEncoder` and `JSONDecoder`. - **`NavigationPath`.** The path is type-erased, so it can't be encoded directly. Its `codable` property returns a `NavigationPath.CodableRepresentation?`. Encode the representation; to restore, decode a `NavigationPath.CodableRepresentation` and pass it to `NavigationPath(_:)`. **Why `codable` can be `nil`.** `NavigationPath.append(_:)` accepts any `Hashable` value; the SDK declares a separate overload for values that are also `Codable`. Apple's guide states that `codable` returns `nil` if any of the path's elements doesn't conform to `Codable`, and that because the path only requires `Hashable`, you can't verify at compile time that it is encodable. One non-`Codable` value, pushed by any feature, makes the whole path unsaveable. A typed array of a `Codable` enum turns this into a compile-time guarantee. ## When and where to save 1. **When.** Apple's `NavigationPath` example saves when the scene's `scenePhase` becomes `.background`; its navigation-stack guide instead saves on every change from a `didSet`. Either works; saving on background is cheaper. 2. **Where.** `@SceneStorage` accepts `Data`, keeps a separate value per scene, and is restored by the system, which suits a path on iPad where each window has its own stack. Its documentation says the system makes no guarantee when the data is persisted, that it is destroyed when the scene is explicitly destroyed (Apple's example is removing the snapshot from the iPadOS app switcher), and that it is not for sensitive data. A file in the app's container is the alternative when the path must outlive the scene, but then two windows share one file. 3. **Load.** Decode in a launch hook such as `task`, assign the path, and skip the restore if a deep link has already filled it. ## Keep path elements lightweight Apple's guide warns against using model types as path elements: keep them lightweight and don't use the path to carry data models. For restoration this matters twice: - an encoded `Order` would bring back yesterday's price and status, while an encoded `order(id: "A1")` makes the screen fetch current data; - an ID may now point at something deleted, so each destination needs a not-found or empty state rather than assuming the item exists. ## When decoding fails Saved data outlives your code. Renaming a route case, changing an associated value or reordering cases in a hand-written `Codable` conformance can make an old payload undecodable. Handle the thrown error by starting from an empty path, as Apple's own example does in its `catch`. Do not rely on `try!`, and do not pass the raw `Data` to `NavigationPath(_:)`: `Data` is a sequence of `Hashable` bytes, so that call compiles and builds a path of bytes, not routes. | Step | Typed `[Route]` | `NavigationPath` | |---|---|---| | encodable when | `Route: Codable` (checked by the compiler) | every element pushed was `Codable` (checked at run time) | | encode | `JSONEncoder().encode(path)` | `path.codable`, then encode the representation | | decode | `JSONDecoder().decode([Route].self, from:)` | decode `NavigationPath.CodableRepresentation`, then `NavigationPath(_:)` | | on failure | start from `[]` | start from `NavigationPath()` | ## A checklist for review - Every route value is a small `Codable` enum case holding IDs. - The save handles `codable == nil` instead of force-unwrapping. - Decoding failure resets to the root without crashing. - A deep link that arrives at launch beats the restored path. - Destinations cope with IDs that no longer resolve.

  • A teammate pushes a non-Codable value onto the shared NavigationPath; what breaks, and how would you prevent it?
    The app still navigates, but `path.codable` now returns `nil`, so the next save stores nothing and the stack is lost on relaunch with no error. Prevent it by making every route type `Codable`, by switching to a typed array of a `Codable` enum so the compiler enforces it, or at least by logging when `codable` is `nil` so the gap is visible.
  • Should a restored path include a checkout or payment screen?
    Usually not. Restoration replays screens from identifiers, and some flows depend on in-memory state, such as a payment in progress, that should not come back half-done. Trim such routes before saving or after decoding, so the user lands on the last screen that can be rebuilt safely.

Saving the path is like noting page numbers in a manual rather than photocopying the pages: when you come back you open the current edition at those pages, and if a page was removed you notice instead of reading stale text.

  • Encode NavigationPath directly with JSONEncoder, it is Codable
  • codable returns nil whenever the path mixes route types
  • Store whole Order models in the path so screens open instantly
  • Force-unwrap path.codable since every value is Hashable
  • SceneStorage guarantees the path is saved on every change