<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Budain on Medium]]></title>
        <description><![CDATA[Stories by Kevin Budain on Medium]]></description>
        <link>https://medium.com/@budainkevin?source=rss-1063d16ef183------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ft939qR-m5Rvn9v9HHxyBw.png</url>
            <title>Stories by Kevin Budain on Medium</title>
            <link>https://medium.com/@budainkevin?source=rss-1063d16ef183------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:17:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@budainkevin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing SwiftUI Navigation Without Mounting a Single View]]></title>
            <link>https://medium.com/@budainkevin/testing-swiftui-navigation-without-mounting-a-single-view-43e8ef870716?source=rss-1063d16ef183------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e8ef870716</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Kevin Budain]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 10:45:09 GMT</pubDate>
            <atom:updated>2026-10-16T10:45:09.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xF7KXsDGecReV_xTubRIdQ.png" /></figure><p>Part 5 of the swift-routing series. If you’re new here, start with <a href="https://medium.com/@budainkevin/stop-fighting-swiftui-navigation-a-type-safe-approach-with-swift-routing-7cbd328f0270">Part 1: Type-Safe Navigation in SwiftUI with swift-routing</a>, <a href="https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407">Part 2: The RouteContext Pattern</a>, <a href="https://medium.com/@budainkevin/tab-navigation-in-swiftui-taming-cross-tab-routing-with-tabrouter-dc7b4f595b45">Part 3: Tab Navigation in SwiftUI: Taming Cross-Tab Routing with TabRouter</a>, and <a href="https://medium.com/@budainkevin/splitview-navigation-in-swiftui-taming-sidebar-routing-with-routingsplitview-b19cf97bfa9b">Part 4: SplitView Navigation in SwiftUI: Taming Sidebar Routing with RoutingSplitView</a></p><p>Ask most iOS developers how they test navigation and the honest answer is: they don’t, not really. Maybe a UI test clicks through a happy path once. The actual logic — “tapping this button should push that screen” — usually ships unverified, because testing it the obvious way means mounting a view hierarchy, injecting a fake <em>@Environment</em>, and asserting on whatever <strong>NavigationPath</strong> happens to look like afterward. That’s expensive to write and brittle to maintain, so most teams just… don’t.</p><p><em>swift-routing</em> was built so that doesn’t have to be the tradeoff. Navigation intent is a protocol call (<em>router.push(_:)</em>, <em>router.present(_:)</em>), and protocol calls can be recorded by a test double, same as any other dependency.</p><h4>The Problem: Navigation Logic Usually Lives Where You Can’t Reach It</h4><p>The most common shape of SwiftUI navigation code puts the decision directly in the view:</p><pre>struct ProfileScreen: View {<br>  @Environment(\.router) private var router<br><br>  var body: some View {<br>    Button(&quot;Edit&quot;) {<br>      router.push(AppRoute.editProfile)<br>    }<br>  }<br>}</pre><p>To verify that tapping “Edit” pushes the right route, you’d need to render <strong>ProfileScreen</strong>, inject a router into its environment, simulate a tap, then inspect whatever that router ended up with — a view-hosting test, slow and fiddly, for a one-line assertion about intent. The view itself doesn’t need testing here; the <em>AppRoute.editProfile</em> decision does.</p><h4>RouterSpy: A RouterModel That Records Instead of Navigates</h4><p><em>SwiftRoutingTestSupport</em> ships <em>RouterSpy</em>, a test double conforming to the full <em>RouterModel</em> protocol — push, present, cover, context handling, split selections, all of it — that records every call instead of performing real navigation:</p><pre>import SwiftRoutingTestSupport<br><br>let spy = RouterSpy(root: AppRoute.home)<br>spy.push(AppRoute.profile(userId: &quot;123&quot;))<br><br>#expect(spy.pushedRoutes.count == 1)<br>#expect((spy.pushedRoutes.first as? AppRoute) == .profile(userId: &quot;123&quot;))</pre><p><em>pushedRoutes</em>, <em>presentedRoutes</em>, <em>coveredRoutes</em>, <em>updatedRoots</em>, <em>backCallCount</em>, <em>popToRootCallCount</em>, <em>closeCallCount</em>, <em>terminatedContexts</em>, <em>dispatchedContexts</em>, <em>contentSelections</em>, <em>detailSelections</em> — the full surface of <em>RouterModel</em> has a recorded counterpart. <em>RouterModel</em> is a protocol with real breadth by now (push, present, cover, context handling, split selections), and a hand-rolled mock for it silently drifts out of sync every time the protocol grows a member. <em>RouterSpy</em> is tested against the real protocol, so it can’t drift the way a one-off mock would.</p><p>One honest limitation: <em>tabRouter(for:)</em>, <em>findRouterInTabRouter(for:)</em>, and <em>deepestRouter()</em> always return <em>nil</em> on a spy — there’s no real router hierarchy behind it. Code that genuinely needs to walk a router tree still wants a real <em>Router</em> in the test.</p><h4>The Pattern That Makes This Possible: Inject, Don’t Reach</h4><p>A spy is only useful if the code under test can receive one instead of a real router — which means the navigation decision has to live somewhere other than <em>@Environment(\.router)</em> read straight from a view’s <strong>body</strong>. The fix is a ViewModel that takes <em>any RouterModel</em> through its initializer:</p><pre>final class UserScreenModel {<br>  private(set) var name: String<br>  private let router: any RouterModel<br>  <br>  init(name: String, router: any RouterModel) {<br>    self.name = name<br>    self.router = router<br>  }<br><br>  func pushBen() {<br>    router.push(AppRoute.user(name: &quot;Ben&quot;))<br>  }<br>  <br>  func back() {<br>   router.back()<br>  }<br>  <br>  func popToRoot() {<br>    router.popToRoot()<br>  }<br>}</pre><p>(This is real, shipped code from the swift-routing demo app — not a simplified stand-in.) The view still reads <strong>@Environment(\.router)</strong>, but only once, to construct the real <em>Router</em> and hand it to the model; every navigation decision from then on goes through <em>any RouterModel</em>, a protocol a spy can stand in for just as well as the real thing.</p><pre>// Avoid: concrete type, impossible to substitute in a test<br>init(router: Router) { … }<br><br>// Good: protocol type, a RouterSpy drops right in<br>init(router: any RouterModel) { … }</pre><h4>A Complete Example: Testing a Button’s Navigation Intent</h4><p>Put the two together, and a navigation test is a handful of lines, no view in sight:</p><pre>import Testing<br>import SwiftRoutingTestSupport<br><br>@Suite(&quot;UserScreenModel Navigation&quot;)<br>struct UserScreenModelTests {<br>  @Test @MainActor<br>  func pushBen_pushesUserRoute() {<br>    let spy = RouterSpy(root: AppRoute.home)<br>    let model = UserScreenModel(name: &quot;Ben&quot;, router: spy)<br><br>    model.pushBen()<br><br>    #expect(spy.pushedRoutes.count == 1)<br>    #expect((spy.pushedRoutes.first as? AppRoute) == .user(name: &quot;Ben&quot;))<br>  }<br><br>  @Test@MainActor<br>  func popToRoot_popsToRoot() {<br>    let spy = RouterSpy(root: AppRoute.home)<br>    let model = UserScreenModel(name: &quot;Ben&quot;, router: spy)<br><br>    model.popToRoot()<br><br>    #expect(spy.popToRootCallCount == 1)<br>   }<br>}</pre><p>Favor asserting on intent over implementation. <em>spy.pushedRoutes.contains { ($0 as? AppRoute) == .user(name: “Ben”) }</em> says what the test actually cares about; a count on `spy.pathCount` (how deep the stack got) ties the test to internal bookkeeping that has nothing to do with the behavior you’re verifying.</p><h4>Testing RouteContext and terminate()</h4><p>The <strong>RouteContext</strong> pattern from <a href="https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407">Part 2</a> is just as testable, in two separate halves: the child firing a context, and the parent reacting to one.</p><p>Sending a context from a ViewModel is another spy assertion, same shape as a push:</p><pre>@Test @MainActor<br>func selectUser_terminatesWithContext() {<br>  let spy = RouterSpy(root: AppRoute.userPicker)<br>  let viewModel = UserPickerViewModel(router: spy)<br>  let user = User(id: &quot;1&quot;, name: &quot;John&quot;)<br><br>  viewModel.selectUser(user)<br><br>  #expect(spy.terminatedContexts.count == 1)<br> <br>  let context = spy.terminatedContexts.first as? UserSelectionContext<br>  #expect(context?.selectedUser.id == &quot;1&quot;)<br>}</pre><p>Receiving a context, on the other hand, needs a real <strong>Router</strong> — a spy has nowhere to route a registered handler to, since <em>add(context: perform:) </em>/ <em>context(_:)</em> are about one router’s own bookkeeping, not a call to record:</p><pre>@Test @MainActor<br>func contextHandler_receivesContext() async {<br>  let router = Router(configuration: .default)<br>  var receivedUser: User?<br><br>  router.add(context: UserSelectionContext.self) { context in<br>    receivedUser = context.selectedUser<br>  }<br><br>  router.context(UserSelectionContext(selectedUser: .init(id: &quot;1&quot;, name: &quot;John&quot;)))<br><br>  #expect(receivedUser?.id == &quot;1&quot;)<br>}</pre><p>That split — spy for sending, real router for receiving — is the same rule of thumb as the <em>tabRouter(for:)</em> limitation above: anything that’s genuinely a call out gets recorded by the spy; anything that depends on a live router’s own state needs the real thing.</p><h4>Testing Across Tabs: TabRouterSpy</h4><p><strong>TabRouterSpy</strong>, from the same package, conforms to <strong>TabRouterModel</strong> the same way <strong>RouterSpy</strong> conforms to <strong>RouterModel</strong> — push/present/cover land in the recorded arrays, but each entry also carries which tab it targeted:</p><pre>@Test @MainActor<br>func crossTabNavigation_pushesToCorrectTab() {<br>  let spy = TabRouterSpy(root: AppRoute.home)<br>  let viewModel = HomeViewModel(tabRouter: spy)<br><br>  viewModel.goToProfile(userId: &quot;123&quot;)<br><br>  #expect(spy.pushedRoutes.count == 1)<br> <br>  let call = spy.pushedRoutes.first<br> <br>  #expect((call?.route as? AppRoute) == .profile(userId: &quot;123&quot;))<br>  #expect((call?.tab as? AppTab) == .profile)<br>}</pre><p>That second assertion — which tab the push targeted, not just which route — is exactly the kind of thing that’s tedious to verify through a mounted view and free once the test is just reading a recorded array.</p><h4>Before and After</h4><p>Before — can’t test this without a window:</p><pre>struct ProfileScreen: View {<br><br>  @Environment(\.router) private var router<br><br>  var body: some View {<br>    Button(&quot;Edit&quot;) {<br>      router.push(AppRoute.editProfile)<br>    }<br>  }<br>}</pre><p>After — the decision moved out of the view, and testing it is three lines:</p><pre>final class ProfileViewModel {<br>  private let router: any RouterModel<br>  <br>  init(router: any RouterModel) {<br>    self.router = router<br>  }<br> <br>  func editProfile() {<br>    router.push(AppRoute.editProfile)<br>  }<br>}<br><br>let spy = RouterSpy(root: AppRoute.profile)<br><br>ProfileViewModel(router: spy).editProfile()<br><br>#expect((spy.pushedRoutes.first as? AppRoute) == .editProfile)</pre><p>Nothing about the view changed in spirit — <em>Button(“Edit”) { viewModel.editProfile() }</em> reads just as plainly as the original. What changed is that the one line that decides where “Edit” goes now lives somewhere a test can reach it directly.</p><h4>Why This Matters</h4><p>The reason navigation usually goes untested isn’t that it doesn’t matter — a button pushing the wrong screen is a real, user-facing bug. It’s that the obvious way to test it is expensive enough that it quietly stops happening. Moving the decision behind a protocol and recording calls instead of performing them removes that cost entirely: no view hierarchy, no simulated taps, no <em>@Environment</em> to fake — just a spy and an assertion about what was supposed to happen.</p><p>That’s the whole idea behind <strong>RouterModel </strong>/ <strong>TabRouterModel</strong> being protocols in the first place, not an afterthought bolted on for tests: the same seam that lets `RouterSpy` stand in for a `Router` is the one that makes the real thing work.</p><p>The library is open source — explore the code, open issues, or contribute: <a href="https://github.com/lowki93/swift-routing">github.com/lowki93/swift-routing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e8ef870716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SplitView Navigation in SwiftUI: Taming Sidebar Routing with RoutingSplitView]]></title>
            <link>https://medium.com/@budainkevin/splitview-navigation-in-swiftui-taming-sidebar-routing-with-routingsplitview-b19cf97bfa9b?source=rss-1063d16ef183------2</link>
            <guid isPermaLink="false">https://medium.com/p/b19cf97bfa9b</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kevin Budain]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 05:01:02 GMT</pubDate>
            <atom:updated>2026-10-12T05:01:02.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJjm5EH5z8cFVXcASSxbjA.png" /></figure><p>Part 4 of the swift-routing series. If you’re new here, start with <a href="https://medium.com/@budainkevin/stop-fighting-swiftui-navigation-a-type-safe-approach-with-swift-routing-7cbd328f0270">Part 1: Type-Safe Navigation in SwiftUI with swift-routing</a>, <a href="https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407">Part 2: The RouteContext Pattern</a>, and <a href="https://medium.com/@budainkevin/tab-navigation-in-swiftui-taming-cross-tab-routing-with-tabrouter-dc7b4f595b45">Part 3: Tab Navigation in SwiftUI: Taming Cross-Tab Routing with TabRouter</a>.</p><p>This one covers the other kind of multi-column app: sidebar, content, and detail on iPad and Mac.</p><p>Every Mail-like or Notes-like app on iPad and Mac faces the same three-column problem: a sidebar picks a folder, the folder picks a list of items, an item picks a detail view — and on iPhone, all three collapse into a single pushed stack. SwiftUI gives you <strong>NavigationSplitView</strong> to draw the columns. It gives you nothing to keep their selections in sync, coordinate them from outside the view that owns them, or handle the iPhone case without writing the same <strong>if isCompact</strong> branch in every screen that touches selection.</p><p><strong>RoutingSplitView</strong> is swift-routing ’s answer: one router, shared across all three columns, the same <strong>push</strong>/<strong>present</strong>/<strong>cover</strong> API you already know, plus typed selection bindings for content and detail.</p><h4>The Problem: NavigationSplitView’s Selection State Is Yours to Manage</h4><p>A typical 3-column setup starts innocently enough:</p><pre>struct ContentView: View {<br>  @State private var selectedFolder: Folder?<br>  @State private var selectedNote: Note?<br><br>  var body: some View {<br>    NavigationSplitView {<br>      List(folders, selection: $selectedFolder) { folder in<br>        Text(folder.name).tag(folder)<br>      }<br>    } content: {<br>      if let selectedFolder {<br>        List(selectedFolder.notes, selection: $selectedNote) { note in<br>          Text(note.title).tag(note)<br>        }<br>      }<br>    } detail: {<br>      if let selectedNote {<br>        NoteDetailView(note: selectedNote)<br>      }<br>    }<br>  }<br>}</pre><p>It works, until something <strong>outside</strong> this view needs to drive a selection — a push notification that should open a specific note, a “View in Notes” button from a share sheet, a deep link. None of that state is reachable from anywhere else; it’s private <em>@State</em> sitting in whichever view happens to own the <strong>NavigationSplitView</strong>. You end up threading bindings down, or reaching for a shared<em> @Observable</em> model that exists purely to route around SwiftUI’s own state ownership rules.</p><p>Then there’s iPhone. <strong>NavigationSplitView</strong> collapses to a single column there, and the auto-selection that makes sense on iPad — select the first folder, then its first note, so the detail column isn’t empty — actively fights the user on iPhone, since it pushes them straight past the folder list they were about to tap through themselves.</p><h4>RoutingSplitView: One Router, Three Columns</h4><p><strong>RoutingSplitView</strong> gives sidebar, content, and detail a single shared, split-type <strong>Router</strong>, injected into the environment the same way as everywhere else in swift-routing:</p><pre>@Environment(\.router) var router</pre><p>2-column (sidebar + detail):</p><pre>RoutingSplitView(destination: AppRoute.self, sidebar: .sidebar) { (folder: Folder) in<br>  AppRoute.notes(folder)<br>}</pre><p>3-column (sidebar + content + detail) — add a <em>detail</em> closure and the middle column appears, driven by whatever the content closure returns:</p><pre>RoutingSplitView(destination: AppRoute.self, sidebar: .sidebar) { (folder: Folder) in<br>  AppRoute.notes(folder)<br>} detail: { (note: Note) in<br>  AppRoute.note(note)<br>}</pre><p>Same router, same environment key, in both cases — the number of trailing closures you provide is what decides the layout, not a different type you have to learn.</p><h4>Driving Selections</h4><p><em>router.detailBinding(as:)</em> and <em>router.contentBinding(as:)</em> wire a <strong>List</strong> selection directly, exactly like SwiftUI&#39;s own <em>selection</em>: parameter — because that&#39;s what they are under the hood:</p><pre>struct SidebarScreen: View {<br>  @Environment(\.router) var router<br>  let folders: [Folder] = Folder.all<br><br>  var body: some View {<br>    List(folders, selection: router.detailBinding(as: Folder.self)) { folder in<br>      NavigationLink(folder.name, value: folder)<br>    }<br>    .onFirstAppear {<br>      guard !router.isCompact else { return }<br>      router.select(detail: folders.first)<br>    }<br>  }<br>}</pre><p>Tapping a row and calling <em>router.select(detail:)</em> programmatically goes through the same path — a selection made by a tap logs the same <em>.navigation</em> event a manual call would, so there’s nothing separate to test or reason about.</p><p>When a screen needs to work for either layout, <em>router.hasContentColumn</em> tells you which column you’re actually driving:</p><pre>if router.hasContentColumn {<br>  router.select(content: folder)<br>} else {<br>  router.select(detail: folder)<br>}</pre><p>This is the same branch <strong>SidebarScreen</strong> needs in a real 2-vs-3-column app: in 3-column mode the sidebar’s selection lands in the content column (the folder’s note list); in 2-column mode there’s no content column, so the sidebar’s selection lands directly in detail.</p><h4>Compact Mode: Don’t Auto-Select on iPhone</h4><p>That <em>guard !router.isCompact else { return }</em> above isn’t defensive boilerplate — it’s the whole reason compact mode doesn’t feel broken. <strong>NavigationSplitView</strong> collapses to one column on iPhone, and <em>router.isCompact</em> reflects <em>horizontalSizeClass</em> (it updates live during iPad multitasking too, not just at launch). Skip the guard, and the same auto-select-first-item logic that makes an iPad app open straight to something useful will, on iPhone, yank the user two screens deep before they’ve tapped anything.</p><p>One property, checked once, and both platforms get the behavior that’s actually right for them — no <em>#if os(iOS)</em> branching on idiom, no separate iPhone code path to maintain.</p><h4>Navigating and Presenting From Any Column</h4><p>Since sidebar, content, and detail all share the <strong>same</strong> router, <em>router.push(_:)</em> always pushes onto the one navigation stack that exists — and that stack only ever renders in the detail column. Push from the sidebar’s own code, and it still shows up in detail, not as a new sidebar screen.</p><p><em>router.present(_:)</em> and <em>router.cover(_:)</em> work the same way, router-wide rather than per-column: call either from any of the three columns, and you get one sheet or cover over the whole split view, not three independent presentation layers to keep untangled.</p><h4>Before and After</h4><p>A concrete trigger: something outside the split view — a “View in Notes” button from a share sheet, say — needs to open the app on a specific folder and note, in whichever column layout is currently showing.</p><p>Before — three pieces of state, and a compact-mode branch to get right by hand:</p><pre>final class PendingSelection: ObservableObject {<br>  @Published var pendingFolder: Folder?<br>  @Published var pendingNote: Note?<br>}<br><br>// Somewhere near the root<br>func openNote(_ note: Note) {<br>  pendingSelection.pendingFolder = note.folder<br>  pendingSelection.pendingNote = note<br>}<br><br>// Inside the view that owns selectedFolder/selectedNote<br>.onChange(of: pendingSelection.pendingNote) { _, note in<br>  guard let note else { return }<br>  selectedFolder = note.folder<br>  selectedNote = horizontalSizeClass == .compact ? nil : note<br>  // ...and now decide, by hand, how to push onto whatever stack<br>  // is currently visible in compact mode, separately from this.<br>}</pre><p>After — two calls on the router, layout-agnostic:</p><pre>final class NoteOpener {<br>  let router: any RouterModel<br><br>  func openNote(_ note: Note) {<br>    router.select(content: note.folder)<br>    router.select(detail: note)<br>  }<br>}</pre><p><em>select(content:)</em> already no-ops safely if the router has no content column, so the same two calls work whether the app is currently showing 2 or 3 columns — no <em>horizontalSizeClass</em> check, no separate compact-mode branch to keep in sync with the one in <strong>SidebarScreen</strong>, and no extra state to own: <strong>NoteOpener</strong> doesn’t need to be a view or touch SwiftUI at all.</p><h4>Why This Matters</h4><p>Sidebar/content/detail navigation is the default shape for any serious iPad or Mac app, and it’s noticeably less covered than tab-based navigation — most SwiftUI navigation writing stops at <strong>NavigationStack</strong>. The gap isn’t whether <strong>NavigationSplitView</strong> can do this; it’s that keeping three columns’ selections coherent, reachable from outside the view that draws them, and correct in compact mode is left entirely to you.</p><p><strong>RoutingSplitView</strong> closes that gap the same way the rest of swift-routing does: one router, typed selections instead of loose <em>@State</em>, reachable from anywhere — on iPad, on Mac, and on iPhone once it collapses.</p><p>The library is open source — explore the code, open issues, or contribute: <a href="https://github.com/lowki93/swift-routing">github.com/lowki93/swift-routing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b19cf97bfa9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tab Navigation in SwiftUI: Taming Cross-Tab Routing with TabRouter]]></title>
            <link>https://medium.com/@budainkevin/tab-navigation-in-swiftui-taming-cross-tab-routing-with-tabrouter-dc7b4f595b45?source=rss-1063d16ef183------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc7b4f595b45</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kevin Budain]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 14:00:16 GMT</pubDate>
            <atom:updated>2026-09-16T14:00:16.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miwMYkkB7manUCYtlIDrNQ.png" /></figure><p>Part 3 of the swift-routing series. If you’re new here, start with <a href="https://medium.com/@budainkevin/stop-fighting-swiftui-navigation-a-type-safe-approach-with-swift-routing-7cbd328f0270">Part 1: Type-Safe Navigation in SwiftUI with swift-routing</a> and <a href="https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407">Part 2: The RouteContext</a>.</p><p>Every app with a tab bar eventually needs to do something SwiftUI’s <strong>TabView</strong> was never designed for: switch to a different tab <strong>and</strong> push a screen inside it, from a single button tap somewhere else entirely. A push notification lands on the Profile tab while you’re browsing Home. A “View order” button in a confirmation sheet needs to land three levels deep in the Orders tab. The already-selected tab needs to pop to root when tapped again — but only sometimes.</p><p><strong>TabView</strong> alone gives you none of this. Swift-routing gives you <strong>TabRouter</strong>.</p><h4>The Problem: TabView Has No Memory of Its Own Structure</h4><p>A plain <strong>TabView</strong> only knows one thing: which tab is currently selected.</p><pre>struct ContentView: View {<br>  @State private var selectedTab: HomeTab = .home<br>  <br>  var body: some View {<br>    TabView(selection: $selectedTab) {<br>      HomeView().tabItem { Label(&quot;Home&quot;, systemImage: &quot;house&quot;) }<br>      SearchView().tabItem { Label(&quot;Search&quot;, systemImage: &quot;magnifyingglass&quot;) }<br>      ProfileView().tabItem { Label(&quot;Profile&quot;, systemImage: &quot;person&quot;) }<br>    }<br>  }<br>}</pre><p>That’s it. There’s no API for “push a screen in the Profile tab while I’m on Home.” Each tab manages its own <strong>NavigationStack</strong> in isolation, and nothing outside that tab can reach into it. If <strong>HomeView</strong> needs to react to a notification tap by opening a specific order inside the Orders tab, you’re on your own — usually some combination of <a href="http://twitter.com/State"><em>@State</em></a> hoisted to a shared ancestor, a <em>PassthroughSubject</em>, and a prayer that the timing works out once the tab has actually mounted.</p><p>Tapping the currently-selected tab again is its own separate problem: SwiftUI gives you no hook for it at all.</p><h4>RoutingTabView + TabRouter: One Router Per Tab</h4><p><strong>RoutingTabView</strong> gives every tab its own <strong>Router</strong>, all coordinated by a parent <strong>TabRouter</strong>:</p><pre>enum HomeTab: TabRoute {<br>  case home<br>  case search<br>  case profile<br><br>  var name: String {<br>    switch self {<br>    case .home: &quot;Home&quot;<br>    case .search: &quot;Search&quot;<br>    case .profile: &quot;Profile&quot;<br>    }<br>  }<br>}<br><br>struct ContentView: View {<br>  @State private var selectedTab: HomeTab = .home<br><br>  var body: some View {<br>    RoutingTabView(tab: $selectedTab, destination: HomeRoute.self) {<br>      RoutingView(tab: HomeTab.home, destination: $0, root: .home)<br>        .tabItem { Label(&quot;Home&quot;, systemImage: &quot;house&quot;) }<br><br>      RoutingView(tab: HomeTab.search, destination: $0, root: .search)<br>        .tabItem { Label(&quot;Search&quot;, systemImage: &quot;magnifyingglass&quot;) }<br><br>      RoutingView(tab: HomeTab.profile, destination: $0, root: .profile)<br>        .tabItem { Label(&quot;Profile&quot;, systemImage: &quot;person&quot;) }<br>    }<br>  }<br>}</pre><p>From any view inside that hierarchy, <a href="http://twitter.com/Environment"><em>@Environment</em></a><em>(\.tabRouter)</em> gives you a handle that can reach <strong>any</strong> tab, not just the current one:</p><pre>struct SomeView: View {<br>  @Environment(\.tabRouter) private var tabRouter<br><br>  var body: some View {<br>    Button(&quot;Go to Profile&quot;) {<br>      tabRouter?.push(HomeRoute.settings, in: HomeTab.profile)<br>    }<br>  }<br>}</pre><p><strong>tabRouter</strong> is optional by design — it’s only available inside a <strong>RoutingTabView</strong>. A view that might be reused outside a tab context (or in a plain push/present flow) still compiles; it just no-ops if there’s no tab router around.</p><h4>Cross-Tab Actions, Concretely</h4><p>Every mutating method on <strong>TabRouter</strong> takes an optional tab:</p><ul><li>change(tab:) — Switch to a different tab</li><li>push(_:in:)<em> — </em>Push a route in a specific tab</li><li>present(_:in:)<em> — </em>Present a sheet in a specific tab</li><li>cover(_:in:)<em> — </em>Present a full-screen cover in a specific tab</li><li>update(root:in:)<em> — </em>Replace the root of a specific tab</li><li>popToRoot(in:)<em> — </em>Pop a specific tab back to its root</li></ul><p>Pass <strong>nil</strong> for <strong>tab</strong> to target whichever tab is currently selected. Pass an explicit tab, and — for every method except <em>popToRoot(in:)</em> — <strong>TabRouter</strong> switches to it first, then acts:</p><pre>// Switches to .profile, THEN pushes<br>// the user sees the tab change and land on settings.<br>tabRouter.push(AppRoute.user(name: &quot;Joseph&quot;), in: HomeTab.profile)<br><br>// Presents a sheet in the notifications tab without leaving the current tab.<br>tabRouter.present(AppRoute.search, in: HomeTab.notifications)<br><br>// Resets the home tab&#39;s stack WITHOUT switching to it<br>// you stay exactly where you are.<br>tabRouter.popToRoot(in: HomeTab.home)</pre><p>That last one is a deliberate exception, not an oversight. <em>popToRoot(in:)</em> is the one method that never calls <em>change(tab:)</em> — resetting a tab you’re not looking at (say, clearing the Home stack when a session expires) shouldn’t yank the user away from what they’re doing.</p><p>The swift-routing demo app’s <strong>ProfileScreen</strong> exercises four of these side by side, injecting <strong>any TabRouterModel</strong> into a view model instead of reading <a href="http://twitter.com/Environment"><em>@Environment</em></a><em>(\.tabRouter)</em> straight from the view — the same pattern the rest of the series leans on, and one that keeps navigation testable without mounting a single view:</p><pre>struct ProfileScreen: View {<br>  let viewModel: ProfileViewModel<br><br>  var body: some View {<br>    VStack {<br>      Button(&quot;Present search (current tab)&quot;) { viewModel.presentSearch() }<br>      Button(&quot;Cover about (current tab)&quot;) { viewModel.coverAbout() }<br>      Button(&quot;Present search in notifications tab&quot;) { viewModel.presentSearchInNotifications() }<br>      // popToRoot(in:) does NOT call change(tab:) -- unlike push/present/cover/update,<br>      // this resets the home tab&#39;s stack without switching you to it.<br>      Button(&quot;Reset home tab (stays on profile)&quot;) { viewModel.resetHomeTab() }<br>    }<br>    .navigationTitle(&quot;Profile&quot;)<br>  }<br>}<br><br>@MainActor<br>final class ProfileViewModel {<br>  private let tabRouter: (any TabRouterModel)?<br><br>  init(tabRouter: (any TabRouterModel)?) {<br>    self.tabRouter = tabRouter<br>  }<br><br>  func presentSearch() {<br>    // current tab<br>    tabRouter?.present(AppRoute.search)<br>  }<br><br>  func coverAbout() {<br>    // current tab<br>    tabRouter?.cover(AppRoute.about)<br>  }<br><br>  func presentSearchInNotifications() {<br>    // switches tab first<br>    tabRouter?.present(AppRoute.search, in: HomeTab.notifications)<br>  }<br><br>  func resetHomeTab() {<br>    // never switches tab<br>    tabRouter?.popToRoot(in: HomeTab.home)                           <br>  }<br>}</pre><p>our buttons, four distinct tab behaviors, and not one of them needed a <strong>NavigationStack</strong> binding threaded in from outside.</p><h4>Reacting to Tab Reselection</h4><p>Tapping the already-selected tab is a UX convention users expect to do <strong>something</strong> — usually scroll to top, sometimes reset a filter. SwiftUI’s <strong>TabView</strong> doesn’t expose this as an event at all.</p><p><em>onTabReselected(_:perform:)</em> does, without touching the default pop-to-root behavior:</p><pre>struct HomeView: View {<br>  @ScrollViewProxy var scrollProxy<br><br>  var body: some View {<br>    ScrollView {<br>      // ...<br>    }<br>    .onTabReselected(HomeTab.home) {<br>      scrollProxy.scrollTo(&quot;top&quot;, anchor: .top)<br>    }<br>  }<br>}</pre><p>The handler fires <strong>after</strong> the stack has already popped to root, and only when the reselected tab matches the one you passed. It works identically whether you’re using <strong>RoutingTabView</strong> or the native <strong>TabView</strong> + <strong>.tabToRoot</strong> binding described below — same modifier, same guarantee, wherever the tab bar lives.</p><h4>Don’t Need Cross-Tab Actions? Use Native TabView</h4><p>Not every tabbed app needs a <strong>TabRouter</strong>. If tabs never need to talk to each other — no cross-tab push, no cross-tab present — SwiftUI’s own <strong>TabView</strong> works fine, with one addition: the <strong>.tabToRoot</strong> binding.</p><pre>struct ContentView: View {<br>  @Environment(\.router) private var router<br>  @State private var selectedTab: HomeTab = .home<br><br>  var body: some View {<br>    TabView(selection: .tabToRoot(for: $selectedTab, in: router)) {<br>      RoutingView(tab: HomeTab.home, destination: HomeRoute.self, root: .home)<br>        .tabItem { Label(&quot;Home&quot;, systemImage: &quot;house&quot;) }<br><br>      RoutingView(tab: HomeTab.search, destination: HomeRoute.self, root: .search)<br>        .tabItem { Label(&quot;Search&quot;, systemImage: &quot;magnifyingglass&quot;) }<br><br>      RoutingView(tab: HomeTab.profile, destination: HomeRoute.self, root: .profile)<br>        .tabItem { Label(&quot;Profile&quot;, systemImage: &quot;person&quot;) }<br>    }<br>  }<br>}</pre><p><strong>.tabToRoot</strong> gives you the reselect-to-reset behavior for free, and each <strong>RoutingView(tab:destination:root:)</strong> still gets its own independent <strong>Router</strong> and <strong>NavigationStack</strong>. What you lose is <a href="http://twitter.com/Environment"><em>@Environment</em></a><em>(\.tabRouter)</em> — there’s no <strong>TabRouter</strong> instance published into the environment, because there’s no shared coordinator to publish. Reach for <strong>RoutingTabView</strong> the moment any of your tabs need to act on another one; stick with native <strong>TabView</strong> for everything else.</p><h4>Before and After</h4><p>Here’s a common trigger for cross-tab navigation: a “View order” button inside a confirmation sheet needs to dismiss, switch to the Orders tab, and land straight on that order’s detail screen — three actions from one tap, in a tab the sheet itself knows nothing about.</p><p><strong>Before — a shared flag and a race with <em>onAppear</em>:</strong></p><pre>// Somewhere shared, injected into both the confirmation sheet and OrdersView<br>@Observable<br>final class PendingOrderNavigation {<br>  var orderId: String?<br>}<br><br>// ConfirmationSheet<br>Button(&quot;View order&quot;) {<br>  selectedTab = .orders<br>  pendingNavigation.orderId = order.id   // OrdersView may not even be mounted yet<br>  dismiss()<br>}<br><br>// OrdersView — has to guess whether it mounted before or after the flag was set<br>struct OrdersView: View {<br>  @State private var path = NavigationPath()<br><br>  var body: some View {<br>    NavigationStack(path: $path) {<br>      // ...<br>    }<br>    .onAppear { applyPendingNavigationIfNeeded() }<br>    .onChange(of: pendingNavigation.orderId) { applyPendingNavigationIfNeeded() }<br>  }<br><br>  private func applyPendingNavigationIfNeeded() {<br>    guard let orderId = pendingNavigation.orderId else { return }<br>    path.append(orderId)<br>    pendingNavigation.orderId = nil<br>  }<br>}</pre><p><strong>After — one call, no mounting order to reason about:</strong></p><pre>Button(&quot;View order&quot;) {<br>  tabRouter.push(AppRoute.order(id: order.id), in: HomeTab.orders)<br>  dismiss()<br>}</pre><p>Same injection pattern as <strong>ProfileViewModel</strong> above — <strong>NotificationRouter</strong> doesn’t need to be a view or touch SwiftUI at all. <strong>TabRouter</strong> already knows how to switch tabs and push into a tab that hasn’t been visited yet; that’s exactly what <em>push(_:in:)</em> does internally, every time, not just for notifications. No flag to clear, no <em>onAppear</em>/<em>onChange</em> race, no <strong>ProfileView</strong>-specific code required to make it work.</p><h4>Why This Matters</h4><p>None of this is exotic. Cross-tab navigation and reselect-to-reset are things almost every non-trivial tabbed app eventually needs. What’s missing from SwiftUI isn’t the <strong>possibility</strong> of building them — it’s a consistent, typed way to do it that doesn’t turn into a pile of <em>@State</em> and <strong>NotificationCenter</strong> posts the third time a new cross-tab flow shows up.</p><p><strong>TabRouter</strong> is the same idea as the rest of swift-routing, applied to tabs: routes as values, and a router that knows how to apply them across tab boundaries. One less category of navigation code that has to be reinvented per app.</p><p><strong>Deep linking into a specific tab, and testing cross-tab navigation with <em>TabRouterSpy</em>, are their own topics — coming up later in this series.</strong></p><p>The library is open source — explore the code, open issues, or contribute: <a href="https://github.com/lowki93/swift-routing">github.com/lowki93/swift-routing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc7b4f595b45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two-Way Navigation in SwiftUI: The RouteContext Pattern]]></title>
            <link>https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407?source=rss-1063d16ef183------2</link>
            <guid isPermaLink="false">https://medium.com/p/0af28310b407</guid>
            <dc:creator><![CDATA[Kevin Budain]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-09-16T14:03:38.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNoXWAEDMrZZsVEI_YQjog.png" /></figure><p>Part 2 of the swift-routing series. If you’re new here, start with <a href="https://medium.com/@budainkevin/stop-fighting-swiftui-navigation-a-type-safe-approach-with-swift-routing-7cbd328f0270">Part 1: Type-Safe Navigation in SwiftUI with swift-routing</a></p><p>Navigation in SwiftUI is a one-way street by default. You push a screen, it does something, and then… You have no clean way to return the result.</p><p>The usual workarounds — shared state, closures passed as parameters, @Binding threaded down the stack — work for simple cases. But they break down fast. Closures couple screens together. Shared state is hard to reason about. @Binding leaks presentation concerns into your view hierarchy.</p><p>Swift-routing solves this with <strong>routeContext:</strong> a typed, structured way for child routes to send data back to any parent in the hierarchy.</p><h4>The Problem: Getting Data Back from a Screen</h4><p>Here’s a common scenario. You have a list of users. You present a picker screen. The user selects someone. You need to restore that selection to the parent.</p><p>The current approach:</p><pre>// ParentView.swift<br>struct ParentView: View {<br>  @State private var selectedUser: User?<br>  @State private var showingPicker = false<br><br>  var body: some View {<br>    Button(&quot;Pick user&quot;) { showingPicker = true }<br>      .sheet(isPresented: $showingPicker) {<br>          UserPickerView(onSelect: { user in<br>              selectedUser = user<br>              showingPicker = false<br>          })<br>      }<br>  }<br>}<br><br>// UserPickerView.swift<br>struct UserPickerView: View {<br>  let onSelect: (User) -&gt; Void<br>  // ...<br>}</pre><p>This works. But <em>UserPickerView</em> now requires a closure to be injected by whoever presents it. If the picker sits three levels deep in the stack, every intermediate screen has to forward that closure down — screens that have nothing to do with the selection. And in tests, verifying the result means triggering the callback manually instead of asserting on a plain value.</p><h4>RouteContext: Data as a First-Class Value</h4><p><strong>RouteContext</strong> inverts the flow. With closures, the parent says: &quot;Here&#39;s what to call when you&#39;re done&quot; — and the child has to accept it. With <strong>RouteContext</strong>, the parent says: &quot;I&#39;m listening for this type of value&quot; — and the child just fires it, without knowing who&#39;s listening..</p><p>Define your context type — any <em>Hashable &amp; Sendable</em> struct works:</p><pre>struct UserSelectionContext: RouteContext {<br>   let user: User<br>}</pre><p>In the parent, register an observer before navigating:</p><pre>struct ParentView: View {<br>  @Environment(\.router) private var router<br>  @State private var selectedUser: User?<br>  <br>  var body: some View {<br>    Button(&quot;Pick user&quot;) {<br>      router.present(AppRoute.userPicker)<br>    }<br>    .routerContext(UserSelectionContext.self) { context in<br>      selectedUser = context.user<br>    }<br>  }<br>}</pre><p>In the child, fire the context when done:</p><pre>struct UserPickerView: View {<br>  @Environment(\.router) private var router<br>  <br>  var body: some View {<br>    List(users) { user in<br>      Button(user.name) {<br>          router.terminate(UserSelectionContext(user: user))<br>      }<br>    }<br>  }<br>}</pre><p><em>terminate</em> does two things: it executes the context (notifying all registered observers), then navigates back — popping the screen or dismissing the sheet, whichever applies.</p><p><em>UserPickerView</em> knows nothing about its parent. No closure. No binding. No shared state.</p><h4>context vs. terminate</h4><p>Two methods fire a <em>RouteContext</em>. They differ in what happens after:</p><ul><li><em>router.context(_:)</em>: fires context, but no navigation</li><li><em>router.terminate(_:)</em>: fires context and dismiss sheet or pop a right screen.</li></ul><p>Use <strong>context</strong> when you want to notify the parent without ending the flow — for example, updating a live preview as the user types. Use <strong>terminate</strong> when the flow is complete, and the screen should close.</p><pre>// Live update — user is still on the screen<br>router.context(PreviewContext(text: currentText))<br><br>// Flow complete — close and return the result<br>router.terminate(UserSelectionContext(user: selectedUser))</pre><h4>How terminate Navigates Back</h4><p><em>terminate</em> is smarter than a simple <em>back()</em> or <em>close()</em>. It looks up the router hierarchy for the observer that registered the context, then navigates back to exactly that level.</p><p>This means it works correctly across deeply nested navigation:</p><pre>HomeView → CategoryView → SubcategoryView → UserPickerView<br>  ↑ registered observer here</pre><p>Calling <strong>router.terminate(UserSelectionContext(…))</strong> from <strong>UserPickerView</strong> pops all the way back to <strong>HomeView</strong> in one call — not just one level. The intermediate screens are cleared automatically.</p><p>If no registered observer is found in the stack, <em>terminate</em> falls back gracefully: it dismisses the modal if presented, or pops one level otherwise.</p><h4>Observers Propagate Up the Hierarchy</h4><p><em>context</em> and <em>terminate</em> don’t just notify the immediate parent — they walk the entire router hierarchy upward, notifying every ancestor that has registered an observer for that context type.</p><p>This is useful when multiple parts of your app need to react to the same event. A profile update deep in a sheet can propagate back to a tab bar badge count, a list refresh, and a parent view model — all with a single call.</p><pre>// In TabView root — reacts to profile updates anywhere<br>.routerContext(ProfileUpdatedContext.self) { _ in<br>    self?.refreshBadge()<br>}<br><br>// Deep inside a nested sheet<br>router.terminate(ProfileUpdatedContext(user: updatedUser))<br>// → notifies TabView root, any intermediate observers, and closes the sheet</pre><h4>Observers Clean Up Automatically</h4><p>You don’t need to manually remove observers in most cases. When a route is popped from the navigation stack, its associated observers are removed automatically.</p><p>If you need to remove an observer explicitly — for example, if you want to stop listening mid-flow — use <em>remove(context:)</em>:</p><pre>router.remove(context: UserSelectionContext.self)</pre><p>This only removes observers registered at the current route. Observers registered at parent routes are not affected.</p><h4>Before and After</h4><p>Here’s what a “pick a user and return it” flow looks like before and after.</p><p><strong>Before — closure threading:</strong></p><pre>// ParentView.swift<br>struct ParentView: View {<br>  @State private var selectedUser: User?<br><br>  var body: some View {<br>    Button(&quot;Pick&quot;) {<br>        // Must pass closure into navigation<br>    }<br>    .sheet(isPresented: ...) {<br>      UserPickerView { user in   // ← tightly coupled<br>        selectedUser = user<br>      }<br>    }<br>  }<br>}<br><br>// UserPickerView.swift<br>struct UserPickerView: View {<br>  let onSelect: (User) -&gt; Void   // ← must know about parent<br>  // ...<br>}</pre><p><strong>After — RouteContext:</strong></p><pre>// ParentView.swift<br>struct ParentView: View {<br>  @Environment(\.router) private var router<br>  @State private var selectedUser: User?<br><br>  var body: some View {<br>    Button(&quot;Pick&quot;) {<br>      router.present(AppRoute.userPicker)<br>    }<br>    .routerContext(UserSelectionContext.self) { context in<br>      selectedUser = context.user<br>    }<br>  }<br>}<br><br>// UserPickerView.swift<br>struct UserPickerView: View {<br>  @Environment(\.router) private var router   // ← no parent knowledge needed<br><br>  var body: some View {<br>    List(users) { user in<br>      Button(user.name) {<br>         router.terminate(UserSelectionContext(user: user))<br>      }<br>    }<br>  }<br>}</pre><p><strong>UserPickerView</strong> is now completely self-contained. It can be presented from anywhere in the app, and any caller can choose how to handle the result.</p><h4>Why This Works: Dependency Inversion</h4><p>The shift from closures to <strong>RouteContext</strong> isn’t just a stylistic choice — it’s an application of the <strong>Dependency Inversion Principle</strong>.</p><p>With closures, <strong>UserPickerView</strong> depends directly on the parent that created it:</p><pre>ParentView ── provides ──▶ onSelect: (User) -&gt; Void ── injected into ──▶ UserPickerView</pre><p>The child accepts a concrete dependency from above. Change the parent, and the child interface changes with it.</p><p>With <strong>RouteContext</strong>, both sides depend on the abstraction:</p><pre>ParentView ── observes ──▶ UserSelectionContext ◀── fires ── UserPickerView</pre><p>Neither side knows about the other. <strong>UserPickerView</strong> doesn’t know who is listening. <strong>ParentView</strong> doesn’t know who will fire the context. They’re decoupled through a shared type.</p><p>This is what makes <strong>UserPickerView</strong> reusable without modification: it has no parent-specific code to change. And it’s what makes the observer in <strong>ParentView</strong> easy to move or replace — the picker keeps working regardless.</p><h4>Testing Navigation Flows</h4><p>Because <strong>RouteContext</strong> values are plain Swift types, testing a navigation flow doesn’t require UI. You can verify the full round-trip at the unit level:</p><pre>@Test<br>func userSelected_terminate_notifiesParentAndNavigatesBack() {<br>  let router = Router(configuration: .default)<br>  var received: UserSelectionContext?<br><br>  router.add(context: UserSelectionContext.self) { context in<br>      received = context<br>  }<br><br>  router.push(AppRoute.userPicker)<br>  router.terminate(UserSelectionContext(user: .fixture))<br><br>  #expect(received?.user == .fixture)<br>  #expect(router.routeCount == 1)  // back to root<br>}</pre><p>No views. No @State. No async dance. Just a router, an observer, and a value.</p><h4>But What About Shared State?</h4><p>Fair question. A shared @Observable model — injected via the environment — is a perfectly valid way to communicate between screens. In simple flows, it’s the right choice.</p><p>The problem appears when the communication is transient. A user picker doesn’t belong in your app’s global state. It runs, returns a value, and disappears. Injecting a @Observable for that means creating something that exists only to be discarded, and whose lifetime you have to manage manually.</p><p><strong>RouteContext</strong> makes the scope explicit: an observer is registered before navigating and removed when the route is popped. The value flows up, the screen closes, and there’s nothing left to clean up. It’s not a replacement for shared state — it’s the right tool when shared state is too much.</p><p>The library is open source — explore the code, open issues, or contribute: <a href="https://github.com/lowki93/swift-routing">github.com/lowki93/swift-routing</a></p><p><em>Next: </em><a href="https://medium.com/@budainkevin/tab-navigation-in-swiftui-taming-cross-tab-routing-with-tabrouter-dc7b4f595b45"><em>Tab Navigation in SwiftUI: Taming Cross-Tab Routing with TabRouter</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0af28310b407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Fighting SwiftUI Navigation: A Type-Safe Approach with swift-routing]]></title>
            <link>https://medium.com/@budainkevin/stop-fighting-swiftui-navigation-a-type-safe-approach-with-swift-routing-7cbd328f0270?source=rss-1063d16ef183------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cbd328f0270</guid>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[Kevin Budain]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 14:18:49 GMT</pubDate>
            <atom:updated>2026-08-16T20:06:45.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPuQNmm_MFxzK8kO34Aqkg.png" /></figure><p>A few months ago, while working at Sorare, I ran into a problem that felt minor at first — and then became unavoidable.</p><p>The app was organized into feature frameworks: one for the marketplace, one for the game, one for the card, and more... Each feature owned its screens. Clean, modular, scalable. Except for one thing: to navigate from Feature A to a screen in Feature B, Feature A had to import Feature B. And Feature B sometimes imported Feature A back. Circular dependencies started appearing. The module graph turned into a tangle.</p><p>The solution wasn’t a navigation library — it was a constraint: <strong>routes had to live outside the views they represent</strong>. Once routes became standalone values, features could navigate to each other without importing one another. The dependency problem disappeared.</p><p>That constraint became swift-routing.</p><h4>The Problem with NavigationStack at Scale</h4><p>Even without a modular setup, SwiftUI’s <em>NavigationStack</em> starts showing cracks the moment your app grows. Here’s what a typical multi-screen app looks like:</p><pre>// In SceneDelegate or your root view…<br>@State private var path = NavigationPath()<br><br>NavigationStack(path: $path) {<br>  HomeView()<br>    .navigationDestination(for: String.self) { id in<br>      DetailView(id: id)<br>    }<br>    .navigationDestination(for: SettingsRoute.self) { route in<br>      switch route {<br>      case .general: GeneralSettingsView()<br>      case .notifications: NotificationsView()<br>      case .privacy: PrivacyView()<br>      }<br>   }<br>}</pre><p>Now imagine five features, each with its own destinations. A few problems compound fast:</p><p><strong>1. Routes are strongly-typed or weakly typed.</strong> Passing a <em>String</em> to identify a destination is fragile. There’s no compiler guarantee that the destination exists or that you’re passing the right data.</p><p><strong>2. Navigation logic leaks into views.</strong> <em>HomeView</em> decides how to present the settings screen. <em>ProductView</em> knows that going to checkout requires a full-screen cover. Views accumulate coordination logic that has nothing to do with presentation.</p><p>3. <strong>Features import each other.</strong> If <em>FeatureA</em> wants to navigate to a screen in <em>FeatureB</em>, it imports <em>FeatureB</em> — and if <em>FeatureB</em> ever needs to go back the other way, you have a circular dependency.</p><p><strong>4. It’s untestable.</strong> Navigation state lives inside views, bound to <a href="http://twitter.com/State"><em>@State</em></a>. There’s no clean way to assert that tapping a button triggered the right navigation action.</p><p>Swift-routing solves all four.</p><h4>Routes as Data</h4><p>The core idea is simple: <strong>a route is just a value</strong>.</p><p>You define an enum that represents every destination in your application:</p><pre>enum AppRoute: Route {<br>  case home<br>  case details<br>  case profile(userId: String)<br>  case settings<br>  case onboarding<br><br>  var name: String {<br>    switch self {<br>    case .home: &quot;home&quot;<br>    case .details: &quot;details&quot;<br>    case let .profile(id): &quot;profile(\(id))&quot;<br>    case .settings: &quot;settings&quot;<br>    case .onboarding: &quot;onboarding&quot;<br>    }<br>  }<br>}</pre><p><em>AppRoute</em> is a plain Swift type — hashable, sendable, exhaustive. No strings. No <em>AnyHashable</em>. No ambient state. The compiler tells you immediately if you forget a case.</p><p>In a modular app, this enum lives in a shared module — a <em>Route</em> or <em>AppRoutes</em> target — that every feature can import without importing each other. Feature A says <em>router.push(AppRoute.details)</em> without knowing anything about the checkout feature’s internals.</p><h4>Separating Routes from Views</h4><p>The view mapping lives in a dedicated conformance, isolated from your views:</p><pre>extension AppRoute: RouteDestination {<br>  static func view(for route: AppRoute) -&gt; some View {<br>    switch route {<br>    case .home:<br>      HomeView()<br>    case .details:<br>      DetailsVew()<br>    case let .profile(userId):<br>      ProfileView(userId: userId)<br>    case .settings:<br>      SettingsView()<br>    case .onboarding:<br>      OnboardingView()<br>    }<br>  }<br>}</pre><p>This is the only place that knows which view corresponds to which route. Your views are completely unaware of the navigation structure around them. They don’t know if they were pushed, presented as a sheet, or used as a full-screen cover.</p><p>This separation is what makes the modular architecture work: the <em>AppRoutes</em> module holds the enum, the <em>App</em> or composition root holds the <em>RouteDestination</em> conformance, and feature modules stay isolated.</p><h4>Setting Up the Stack</h4><p>The entry point is <em>RoutingView</em>. Drop it at the top of your scene:</p><pre>@main<br>struct MyApp: App {<br>  var body: some Scene {<br>    WindowGroup {<br>      RoutingView(destination: AppRoute.self, root: .home)<br>    }<br>  }<br>}</pre><p>That single line:<br>- Creates a <em>NavigationStack</em><br>- Instantiates a <em>Router</em> and injects it into the SwiftUI environment<br>- Renders <em>HomeView</em> as the root<br>- Wires up all <em>navigationDestination</em> handlers automatically</p><p>No boilerplate. No manual <em>NavigationPath</em> management.</p><h4>Navigating from Views</h4><p>Inside any view, you access the router from the environment:</p><pre>struct HomeView: View {<br>  @Environment(\.router) private var router<br><br>  var body: some View {<br>    VStack {<br>      Button(&quot;Open Profile&quot;) {<br>        router.push(AppRoute.profile(userId: &quot;42&quot;))<br>      }<br>      Button(&quot;Onboarding&quot;) {<br>        router.cover(AppRoute.onboarding)<br>      }<br>    }<br>  }<br>}</pre><p>The <em>Router</em> covers the full navigation surface:</p><ul><li><em>router.push(_:)</em> - Push onto the stack</li><li><em>router.present(_:) - </em>Present as a sheet</li><li><em>router.cover(_:) - </em>Full-screen cover</li><li><em>router.back() - </em>Pop one level</li><li><em>router.popToRoot() - </em>Clear the entire stack</li><li><em>router.close() - </em>Dismiss a modal</li><li><em>router.update(root:) - </em>Replace the root</li></ul><h4>Before and After</h4><p>Here’s what navigating to a profile looks like before swift-routing:</p><pre>// HomeView.swift - before<br>struct HomeView: View {<br>  @Binding var path: NavigationPath<br><br>  var body: some View {<br>    Button(&quot;Open Profile&quot;) {<br>      path.append(&quot;user-42&quot;) // What is &quot;user-42&quot;? No one knows.<br>    }<br>  }<br>}</pre><p>And after:</p><pre>// HomeView.swift - after<br>struct HomeView: View {<br>  @Environment(\.router) private var router<br><br>  var body: some View {<br>    Button(&quot;Open Profile&quot;) {<br>      router.push(AppRoute.profile(userId: &quot;user-42&quot;)) // Explicit, typed, traceable.<br>    }<br>  }<br>}</pre><p>The call site is self-documenting. The compiler enforces it. And <em>HomeView</em> no longer needs a <a href="http://twitter.com/Binding"><em>@Binding</em></a> injected from above.</p><h4><em>One Router Per Scope, Automatically</em></h4><p>Every <em>RoutingView</em> creates its own <em>Router</em>, scoped to that navigation context.</p><p>When you present a sheet, the sheet gets its own child <em>Router</em>. When that sheet presents another sheet, that too gets its own <em>Router</em>. The routers form a hierarchy that mirrors your navigation tree — and they clean up after themselves automatically when dismissed.</p><p>You never instantiate <em>Router</em> yourself. You just read it from the environment:</p><pre>@Environment(\.router) private var router</pre><p>The right router is always there, always scoped correctly. If you’re inside a sheet, <em>router.close()</em> dismisses the sheet. If you’re inside the main stack, <em>router.back()</em> pops. Same API, context-aware behavior.</p><h4>Routing by Convention</h4><p>Routes can also declare their own presentation style. If <em>settings</em> should always open as a sheet, encode that directly in the route:</p><pre>enum AppRoute: Route {<br>  case home<br>  case settings<br>  <br>  var routingType: RoutingType {<br>    switch self {<br>    case .settings: .sheet(withStack: true)<br>    default: .push<br>    }<br>  }<br>}</pre><p>Then a single call handles everything:</p><pre>// Always opens as a sheet, wherever this is called.<br>router.route(AppRoute.settings)</pre><p>This is useful for establishing conventions in your codebase — “settings is always a sheet” — without scattering that knowledge across call sites. Change your mind later? Update one place.</p><h4>“But What About the Coordinator Pattern?”</h4><p>Fair question. The Coordinator pattern addresses the same root problem — views shouldn’t own navigation — and some SwiftUI-native implementations of it do exist.</p><p>Other solutions give you the stack as an array and wish you luck. Swift Routing bets on convention: routes know how they want to be presented, routers scope themselves, and the boring cases disappear. Control is still there when you need it — it just doesn’t leak into every line of code.</p><h4>What’s Next</h4><p>This is just the foundation. Swift-routing has more to offer:</p><p>- <strong>RouteContext</strong> — a mechanism for child routes to send typed data back to parent routes, without callbacks or shared state<br>- <strong>Deep</strong> <strong>linking</strong> — expressive factory methods that rebuild your navigation stack from a URL or push notification<br>- <strong>Tab navigation</strong> — independent navigation stacks per tab, with cross-tab programmatic control<br>- <strong>Testability</strong> — a <em>RouterModel</em> protocol that makes navigation fully mockable in unit tests</p><h4>Getting Started</h4><p>Add swift-routing via Swift Package Manager:</p><pre>// Package.swift<br>.package(url: &quot;https://github.com/lowki93/swift-routing&quot;, from: &quot;0.2.0&quot;)</pre><p>The full source, documentation, and example app are on <a href="https://github.com/lowki93/swift-routing">GitHub</a>.</p><p><em>Next: </em><a href="https://medium.com/@budainkevin/two-way-navigation-in-swiftui-the-routecontext-pattern-0af28310b407"><em>Two-Way Navigation in SwiftUI: The RouteContext Pattern</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cbd328f0270" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>