<?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 Gonçalo Frade on Medium]]></title>
        <description><![CDATA[Stories by Gonçalo Frade on Medium]]></description>
        <link>https://medium.com/@goncalofrade?source=rss-5800301374f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D9s7VZXlwpYeVjaD</url>
            <title>Stories by Gonçalo Frade on Medium</title>
            <link>https://medium.com/@goncalofrade?source=rss-5800301374f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:23:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@goncalofrade/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[The SMT Manifesto: The Safety Net — Absolute Confidence Through Testing (Part 5)]]></title>
            <link>https://medium.com/@goncalofrade/the-smt-manifesto-the-safety-net-absolute-confidence-through-testing-part-5-fd818bc8d924?source=rss-5800301374f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd818bc8d924</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Gonçalo Frade]]></dc:creator>
            <pubDate>Thu, 07 May 2026 09:51:02 GMT</pubDate>
            <atom:updated>2026-05-07T09:54:22.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znTZMB4AW7SkLW8QP21e4A.png" /></figure><p>We’ve reached the final chapter of the SMT Manifesto. Over the last four articles, we’ve built a powerhouse of an architecture:</p><ul><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-mastering-architectural-foundations-in-swiftui-part-1-9332f61587b1"><strong>Part 1</strong></a><strong>:</strong> We laid the <strong>Foundation</strong> with modularization and dependency injection.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26"><strong>Part 2</strong></a><strong>:</strong> We built the <strong>Logic Engine</strong> using MVVM, Protocols, and Generics.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5"><strong>Part 3</strong></a><strong>:</strong> We mastered the <strong>Traffic Controller</strong> with the Coordinator pattern.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-visual-language-atomic-design-composability-part-4-e747a8f7a132"><strong>Part 4</strong></a><strong>:</strong> We defined the <strong>Visual Language</strong> through Atomic Design.</li></ul><p>Why did we go through all that “extra” work? Because of the T in SMT: Testability. Every protocol, every generic constraint, and every decoupled layer was a strategic move to ensure that we can wrap our application in a safety net of automated tests.<br>Today, we talk about the final piece of the puzzle: The Testing Strategy.</p><h3><strong>Testing as a Team Culture</strong></h3><p>Architecture is only as strong as the team’s willingness to protect it. In a professional environment, SMT is not a solo effort, it is a shared agreement.<br>The goal is to move away from “Subjective Reviews” where a senior developer has to manually check if someone broke a modularity rule and move toward Automated Enforcement. When testing becomes a cultural pillar, the codebase becomes self-validating. It’s no longer about “Is this code good?” but “Does this code satisfy the SMT requirements?”</p><h4><strong>The Testing Philosophy: Assurance, Stability, and Feedback</strong></h4><p>Testing is not about chasing a “100% coverage” badge, that is a vanity metric. At its core, testing is about Assurance. <br>It is the formal proof that your code works as expected under defined conditions.<br>By building a robust suite of tests, you achieve three critical objectives:</p><ol><li><strong>Regression Prevention:</strong> Ensuring that new features or bug fixes don’t silently break existing functionality.</li><li><strong>System Stability:</strong> Creating a predictable environment where the “cost of change” remains low over time.</li><li><strong>Early Feedback:</strong> Identifying errors at the moment of creation rather than weeks later in production.</li></ol><p>When you have assurance, stability, and early feedback, the ultimate byproduct is Developer Velocity. You can move fast because you aren’t constantly looking over your shoulder for what might have broken.</p><h3><strong>The ROI of Testing</strong></h3><p>To achieve this without burning out, you must understand the Return on Investment (ROI) of different test types:</p><ul><li><strong>Unit Tests</strong><br>• <strong>Value:</strong> High (Logic Verification &amp; Correctness)<br>• <strong>Maintenance Cost:</strong> Low<br>• <strong>Recommended Coverage:</strong> 90%+ of Business Logic</li><li><strong>Snapshot Tests</strong><br>• <strong>Value:</strong> High (Visual Consistency &amp; Regression)<br>• <strong>Maintenance Cost:</strong> Medium<br>• <strong>Recommended Coverage:</strong> All Molecules, Organisms &amp; Module Views</li><li><strong>UI Tests</strong><br>• <strong>Value:</strong> Medium (End-to-End Flow Validation)<br>• <strong>Maintenance Cost:</strong> High<br>• <strong>Recommended Coverage:</strong> Critical “Happy Paths” Only</li></ul><h4><strong>1. Unit Testing: Verifying the Brain</strong></h4><p>Unit tests are your first line of defense. They are fast, light, and provide the most granular feedback loop. They verify that your Use Cases and ViewModels handle data, logic, and state transitions exactly as specified.</p><blockquote>The Stability Strategy: Before fixing a bug, write a unit test that reproduces it. Once the fix is applied and the test passes, you have secured that piece of logic against regression forever. In a team context, these are your “PR Shields.”</blockquote><h4><strong>2. Snapshot Testing: The Visual Guard</strong></h4><p>How do you assure that a change in a domain-agnostic Atom (like a global padding update) didn’t break a specific Organism three modules away? You use Snapshot Testing.<br>You can use the pointfreeco/swift-snapshot-testing library to &quot;photograph&quot; your views. Because our architecture uses protocols and generics, we can inject a MockViewModel into our ModuleView and snap it instantly.</p><ul><li><strong>The Value:</strong> Immediate detection of UI regressions. If a pixel moves unexpectedly, the test fails.</li><li><strong>Team Impact:</strong> Reviewers can see a visual “diff” in the Pull Request, providing assurance that the UI looks exactly as intended across different devices and themes.</li></ul><h4><strong>3. UI Tests: The User’s Journey</strong></h4><p>UI tests are the most expensive assets to maintain in your safety net. While some engineering teams successfully implement and manage comprehensive, full-coverage UI test suites, doing so requires a significant sacrifice of time, specialized roles, and high engineering overhead.</p><p>For the majority of teams, the most effective paradigm is to rely on Unit and Snapshot tests to handle the heavy lifting, while utilizing UI Tests to verify the “Money Flows” the critical user journeys like registration, search-to-purchase, or final payment buttons.</p><p>Ultimately, the scope of your UI testing is a strategic team decision. You must weigh the desire for end-to-end automation against the reality of maintenance costs and potential impacts on delivery speed. A focused suite ensures your primary business drivers are protected without turning your CI pipeline into a bottleneck.</p><h3><strong>The SMT Testing Roadmap</strong></h3><p>To build a professional-grade product that delivers stability and quality, follow this priority:</p><ol><li><strong>Protect the Use Cases:</strong> Unit test your business rules until they are bulletproof.</li><li><strong>Validate the Visuals:</strong> Use Snapshots to ensure your Organisms and Views handle different data and themes correctly.</li><li><strong>Verify the Coordination:</strong> Unit test your ViewModels to ensure they coordinate state and trigger navigation correctly.</li><li><strong>Secure the “Money Flows”:</strong> Use UI tests to ensure the user can actually finish their primary tasks.</li></ol><h3><strong>Final Thoughts: The SMT Legacy</strong></h3><p>The SMT Manifesto isn’t just about writing code, it’s about engineering a system that respects your time, your team’s productivity, and your business’s goals. <br>While the core pillars of Scalability, Maintainability, and Testability are the foundation of any professional software, this manifesto provides a concrete, proven roadmap for achieving them specifically within the unique declarative world of SwiftUI.</p><ul><li><strong>Scalability</strong> allows your team to expand and your features to grow without hitting a productivity plateau.</li><li><strong>Maintainability</strong> allows you to evolve the app and swap dependencies with surgical precision and zero side effects.</li><li><strong>Testability</strong> provides the foundational assurance and stability required to ship on Friday and sleep well on Saturday.</li></ul><p>By modularizing your code, decoupling your logic with protocols, and building a consistent visual language, you haven’t just built an app you’ve built a legacy. <br>These principles ensure that your project remains a joy to work on, whether you’re adding the second feature or the two-hundredth.</p><p>Thank you for following this LONG LONG journey. Hope it helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd818bc8d924" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SMT Manifesto: The Visual Language — Atomic Design & Composability (Part 4)]]></title>
            <link>https://medium.com/@goncalofrade/the-smt-manifesto-the-visual-language-atomic-design-composability-part-4-e747a8f7a132?source=rss-5800301374f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e747a8f7a132</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gonçalo Frade]]></dc:creator>
            <pubDate>Wed, 06 May 2026 08:17:30 GMT</pubDate>
            <atom:updated>2026-05-07T09:52:23.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeEsd2_BXDTA8m-55pdMcw.png" /></figure><p>In <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5">Part 3</a>, we mastered the “Traffic Controller”, the Coordinator. We saw how a modular routing framework allows us to decouple navigation from our views, handle complex modal presentations, and implement recursive deep linking without polluting our business logic.</p><p>But even the most sophisticated logic engine is invisible to the user. To satisfy the SMT pillars, our UI needs to be as structured and scalable as our code. Today, we move into the “Visual Language” of our application, there are multiple ways to achieve this, in this article we will talk about applying the principles of Atomic Design to SwiftUI to create a UI that is truly composable, testable, and maintainable.</p><h3><strong>What is Atomic Design?</strong></h3><p>Atomic Design, a methodology popularized by Brad Frost, treats UI components as a hierarchy of building blocks. In the context of SwiftUI, it allows us to stop building “Screens” and start building “Systems.”</p><p>While the original methodology includes five stages, in this article, we primarily focus on three, with our Module Views serving as the final assembly points.</p><h4><strong>1. Atoms: The Foundation</strong></h4><p>Atoms are the smallest building blocks of your UI. They cannot be broken down further without losing their functionality. In SwiftUI, an Atom is often a highly styled wrapper around a native component.</p><ul><li><strong>Examples:</strong> Custom Buttons, Labels, Colors, Typography styles, or specialized Icons.</li><li><strong>The Rule:</strong> Atoms never hold state beyond simple UI interactions (like a hover effect). They are the pure “DNA” of your design system.</li></ul><p>Crucially, Atoms should be completely agnostic to the scope of your app. They don’t know if they are in a shopping app, a banking app, or a fitness tracker. They are named and designed based on their structure, not their business purpose.</p><h4><strong>2. Molecules: The Functional Units</strong></h4><p>Molecules are groups of Atoms bonded together to function as a single unit.</p><ul><li><strong>Examples:</strong> A Search Bar (TextField Atom + Icon Atom), a Labeled Toggle, or a Profile Header (Image Atom + Text Atoms).</li><li><strong>The Rule:</strong> Molecules are responsible for simple layout logic but remain “dumb” regarding business rules.</li></ul><h4><strong>3. Organisms: The Complex Blocks</strong></h4><p>Organisms are distinct, complex UI components made of groups of Molecules and/or Atoms. These form the recognizable sections of your interface.</p><ul><li><strong>Examples:</strong> A Product Card, a Navigation Header, or a complete List Row.</li><li><strong>The Rule:</strong> Organisms define the “Look and Feel” of a feature section. While they handle more layout complexity, they still don’t know where their data comes from.</li></ul><h4><strong>4. Templates &amp; Pages (Our Module Views)</strong></h4><p>In our article, the Module Views we discussed in <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26">Part 2</a> and <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5">Part 3</a> act as the Templates or Pages. These are the “Glue” layers. They take our reusable Organisms and bind them to the ViewModel (for data) and the Coordinator (for navigation).</p><h3><strong>The Golden Rule: No Logic, High Composability</strong></h3><p>To maintain Maintainability (M) and Testability (T), your UI components (Atoms, Molecules, Organisms) must strictly follow two rules:</p><h4><strong>1. Logic-Free Components</strong></h4><p>Your UI components should never inject a service, access a Database, or use @Inject. They should receive exactly what they need to render via their initializer.</p><ul><li><strong>Bad:</strong> A ProfileCard that fetches its own user data.</li><li><strong>Good:</strong> A ProfileCard that takes a User struct or a simple set of strings.</li></ul><h4><strong>2. High Composability via @ViewBuilder</strong></h4><p>A truly scalable UI system is built like LEGO. Use @ViewBuilder to allow components to wrap other content. This makes your UI flexible enough to handle future design changes without a total refactor.</p><pre>// A Molecule example: A Card container that is logic-agnostic<br>struct SMTCard&lt;Content: View&gt;: View {<br>    let title: String<br>    let content: Content<br><br>    init(title: String, @ViewBuilder content: () -&gt; Content) {<br>        self.title = title<br>        self.content = content()<br>    }<br><br>    var body: some View {<br>        VStack(alignment: .leading, spacing: 12) {<br>            Text(title).font(.headline)<br>            content<br>        }<br>        .padding()<br>        .background(Color.secondary.opacity(0.1))<br>        .cornerRadius(12)<br>    }<br>}</pre><h3><strong>Previews: The Living Documentation</strong></h3><p>In <a href="https://www.google.com/search?q=link-to-part-2">Part 2</a>, we discussed using Previews to simulate ViewModel states. Now, we complement that approach by using Previews as a Visual Catalog.</p><p>Because our Atoms and Molecules are “dumb” and logic-free, they are incredibly easy to preview. In a team environment, your UI layer should serve as an interactive visual reference. Every component should provide #Previews for every possible visual state, communicating the &quot;Visual Language&quot; to your colleagues so they can assemble features like LEGO.</p><pre>// MARK: - Interactive Documentation (Previews)<br><br>#Preview(&quot;Atoms / Enum Picker - Default&quot;) {<br>    // Proving that our Atom works for any enum<br>    EnumPicker(selection: .constant(MyExampleEnum.first))<br>}<br><br>#Preview(&quot;Molecules / Stepper - Disabled State&quot;) {<br>    SMTStepper(value: .constant(5), range: 0...10, isEnabled: false)<br>}<br><br>#Preview(&quot;Organisms / Trip Card - Dark Mode&quot;) {<br>    // Testing how the domain-specific component handles themes<br>    TripOrderCard(trip: .mockParis, onDetailsTap: {})<br>        .preferredColorScheme(.dark)<br>}</pre><h4><strong>The SMT Advantage</strong></h4><p>By providing these previews, you enable Testability (T) and Scalability (S). A developer joining the team doesn’t need to run the app to find out how a button looks, they just browse the Atoms folder.</p><h3><strong>Why This Wins for SMT</strong></h3><ul><li><strong>Scalability (S):</strong> When you change the EnumPicker (Atom), every single picker in the app—from settings to checkout—is updated instantly without side effects.</li><li><strong>Maintainability (M):</strong> Logic-free views are “safe.” You can refactor the business logic in your ViewModel without any fear of accidentally changing the padding on a view.</li><li><strong>Testability (T):</strong> Deterministic UI components are perfect for <strong>Snapshot Testing</strong>.</li></ul><h3><strong>Wrapping Up Part 4</strong></h3><p>We have defined the “DNA” of our app’s interface. By strictly separating UI construction (Atoms/Molecules) from UI assembly (Organisms/Module Views), we ensure our visual layer is as robust as our logic layer.<br>But how do we ensure that a change in an Atom doesn’t accidentally break our entire layout?</p><p>Next up in the final <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-safety-net-absolute-confidence-through-testing-part-5-fd818bc8d924">Part 5</a>: The Safety Net. We will look at Unit Tests, UI Tests, and Snapshot Tests to wrap our SMT application in a layer of absolute confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e747a8f7a132" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SMT Manifesto: The Traffic Controller — Mastering SwiftUI Coordination (Part 3)]]></title>
            <link>https://medium.com/@goncalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5?source=rss-5800301374f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a97ed114b5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gonçalo Frade]]></dc:creator>
            <pubDate>Wed, 06 May 2026 08:16:49 GMT</pubDate>
            <atom:updated>2026-05-06T08:24:58.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb_hXzrdBMlaU3ucoZu_Ow.png" /></figure><p>In <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26">Part 2</a>, we focused on the relationship between the View and the ViewModel. We saw how Protocols and Generics turn our UI into a plug-and-play system. But while our View became “dumb” and our ViewModel became “smart,” we left a massive hole in our architecture: Who actually drives the car?</p><p>In most SwiftUI applications, navigation is scattered. You find NavigationLink inside a body property, or a .sheet modifier controlled by a local @State boolean. This is an SMT nightmare. It couples your View to its neighbor, making it impossible to reuse the View in a different context and making Deep Linking a complex puzzle of state-drilling.</p><p>Today, we introduce the Coordinator, the “Traffic Controller” of your application. <br>While many architectural guides advocate for a singular, monolithic “App Coordinator” to handle an entire application’s flow, that approach may create a huge coordinator that violates our core SMT pillars.</p><p>To keep our modules truly independent and scalable, our coordination must follow the same modular pattern. By distributing navigation logic across independent, feature-specific coordinators, we ensure that every module remains a self-contained unit. This doesn’t just manage expectations for your team, it ensures the long-term Maintainability and Scalability of the app as it grows from three screens to three hundred.</p><h3><strong>The Routing System: A Toolbox for Navigation</strong></h3><p>Before we look at the implementation, we need to understand the components that make up a robust routing framework. We aren’t just using a single class, we are using a suite of specialized tools designed to handle every navigation scenario SwiftUI throws at us.<br>The Routing Architecture Components:</p><ul><li><strong>RouteCoordination</strong>: The “Mother” protocol. It associates a Route enum (where you are going) with a Destination view builder (what the screen looks like).</li><li><strong>NavigationRouter</strong>: An Observable class that owns the NavigationPath. This is the actual engine that handles pushing and popping.</li><li><strong>SheetRouter</strong>: Manages active sheet routes, allowing for item-based modal presentations.</li><li><strong>NavigationCoordination</strong>: An extension of the base protocol specifically for stack-based navigation.</li><li><strong>RoutingNavigationStack</strong>: A SwiftUI wrapper that hides the complexity of the NavigationStack and provides the router to the environment.</li><li><strong>SheetCoordination</strong>: Specialized for presenting and dismissing modals.</li><li><strong>TabCoordination</strong>: Handles tab-bar logic where routes must be Identifiable.</li><li><strong>DismissableCoordination</strong>: For when a modally presented feature needs to tell its parent, “I’m done, please close me.”</li></ul><blockquote><strong>Note:</strong> Here is the link for the framework code, check it, use it, change it for what you need: <a href="https://github.com/beatt83/SwiftUICoordination">SwiftUICoordination</a>.</blockquote><h3><strong>The Decoupled View: Setting Requirements</strong></h3><p>In our SMT approach, the View is the one that declares what it needs. It doesn’t care <em>how</em> a screen is pushed, it only cares that it <em>can</em> be pushed. We use Generic constraints to define these “capabilities.”<br>Here is how we update our ExampleView from <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26">Part 2 </a>to support navigation:</p><pre>struct ExampleView&lt;ViewModel: ExampleViewModel, Coordinator: NavigationCoordination&gt;: View {<br>    @State private var viewModel: ViewModel<br>    // The view declares: &quot;I need a Coordinator that can handle Stack Navigation&quot;<br>    @State private var coordinator: Coordinator<br><br>    init(viewModel: ViewModel, coordinator: Coordinator) {<br>        self.viewModel = viewModel<br>        self.coordinator = coordinator<br>    }<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>           // Part 2 code unchanged<br>        }<br>        .padding()<br>        .task {<br>            await viewModel.loadData()<br>        }<br>        // This modifier bridges our Coordinator logic to the SwiftUI NavigationStack<br>        .navigationDestination(coordinator: coordinator)<br>    }<br>}</pre><h4><strong>Composing Capabilities on the Fly</strong></h4><p>The true power of this pattern lies in Composition. In SwiftUI, you often need a screen to do multiple things: push a new view onto the stack <em>and</em> present a modal sheet.<br>In our architecture, the View sets its own capabilities. If you decide that ExampleView now needs to show a sheet, you don&#39;t change the implementation of the View&#39;s logic, you simply update the generic constraint.</p><blockquote>Note: In the example below, notice how the generic Coordinator now conforms to both NavigationCoordination AND SheetCoordination using the &amp; operator.</blockquote><pre>struct ExampleView&lt;ViewModel: ExampleViewModel, Coordinator: NavigationCoordination &amp; SheetCoordination&gt;: View {<br>    @State private var viewModel: ViewModel<br>    @State private var coordinator: Coordinator<br><br>    init(viewModel: ViewModel, coordinator: Coordinator) {<br>        self.viewModel = viewModel<br>        self.coordinator = coordinator<br>    }<br><br>    var body: some View {<br>        // ... previous view content ...<br>        <br>        // By adding these modifiers, the View is now wired to handle <br>        // both Pushes and Sheets via the same Coordinator.<br>        .sheet(coordinator: coordinator)<br>        .navigationDestination(coordinator: coordinator)<br>    }<br>}</pre><p>It is crucial to understand the distinction: The View defines <strong>the requirements (the “what”)</strong>, but the Coordinator provides the <strong>implementation (the “how”)</strong>.</p><h3><strong>Updating the ViewModel: Blind Navigation</strong></h3><p>We need to update our ExampleViewModelImpl from <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26">Part 2</a>. However, we don&#39;t want our ViewModel to depend on the entire routing framework. The ViewModel should remain &quot;blind&quot; to the actual navigation stack, it should only know that it can request a specific transition.<br>We achieve this by creating a localized coordination protocol:</p><pre>// This protocol lives near the ViewModel and defines the specific <br>// navigation actions this feature needs.<br>protocol ExampleViewCoordinator {<br>    func showExample2()<br>}<br><br>@MainActor<br>@Observable<br>final class ExampleViewModelImpl: ExampleViewModel {<br>    // ... existing properties from Part 2 (State, var2, etc.)<br>    <br>    // We depend on our local protocol, not the &#39;NavigationRouter&#39;<br>    private var coordinator: ExampleViewCoordinator<br><br>    init(coordinator: ExampleViewCoordinator) {<br>        self.coordinator = coordinator<br>    }<br><br>    func showExample2Screen() {<br>        // The ViewModel tells the coordinator what the user INTENDS to do.<br>        // It has no idea if this will result in a Push, a Sheet, or a Tab switch.<br>        coordinator.showExample2()<br>    }<br>}</pre><p>By adding this layer, we satisfy the SMT pillars. In a Unit Test, you can pass a MockCoordinator to this ViewModel and simply verify that showExample2() was called. You don&#39;t need to mock a NavigationPath or any SwiftUI components.</p><h3><strong>The Coordinator Implementation: The Assembly Line</strong></h3><p>Now we bring it all together in the concrete Coordinator. This class acts as the “Glue.” It implements the business-specific navigation protocol for the ViewModel AND the routing-framework protocols for the View.</p><pre>// ExampleViewCoordinator.swift<br>import Foundation<br>import SwiftUI<br><br>// 1. Define the possible destinations for this feature<br>enum ExampleRoute: Hashable {<br>    case example2<br>}<br><br>// 2. The Implementation: It satisfies the ViewModel&#39;s needs (ExampleViewCoordinator)<br>// and the View&#39;s needs (NavigationCoordination).<br>@MainActor<br>struct ExampleViewCoordinatorImpl: ExampleViewCoordinator, NavigationCoordination {<br>    <br>    // The Router is the engine provided by the framework<br>    let router: NavigationRouter<br>    <br>    init(router: NavigationRouter) {<br>        self.router = router<br>    }<br>    <br>    // Implementation of the ViewModel&#39;s intent<br>    func showExample2() {<br>        push(route: .example2)<br>    }<br><br>    // Implementation of the RouteCoordination requirement.<br>    // This is the &quot;Factory&quot; where modules are assembled.<br>    @ViewBuilder<br>    func build(_ route: ExampleRoute) -&gt; some View {<br>        switch route {<br>        case .example2:<br>            // This is the beauty of Modularization:<br>            // To start &#39;Example 2&#39;, we assemble its entire SMT triad.<br>            let nextCoordinator = Example2Coordinator(router: router)<br>            let nextViewModel = Example2ViewModel(coordinator: nextCoordinator)<br>            <br>            Example2View(viewModel: nextViewModel, coordinator: nextCoordinator)<br>        }<br>    }<br>}</pre><h3><strong>Expanding the Assembly Line: Sheets and Parameters</strong></h3><p>In a real-world application, navigation isn’t always a simple “push” to a static screen. You will frequently need to present modal sheets and, more importantly, pass data between features.<br>Let’s expand our example. Imagine we want to present a detail view (Example3) as a sheet, and we need to pass a specific id string to it.</p><h4><strong>1. Update the ViewModel Protocol</strong></h4><p>First, we update the local contract. The ViewModel shouldn&#39;t care that this is a &quot;sheet&quot;, it only cares that it needs to &quot;show Example 3&quot; with a specific piece of data.</p><pre>// ExampleViewModel.swift<br><br>protocol ExampleViewCoordinator {<br>    func showExample2()<br>    // The ViewModel now requests navigation with a parameter<br>    func showExample3(_ id: String)<br>}</pre><h4><strong>2. Enhancing the Route and Coordinator</strong></h4><p>To support sheets in this framework, our Route must conform to Identifiable. We also add a SheetRouter to the implementation and update our build logic to handle the new case.</p><pre>// ExampleViewCoordinator.swift<br>import Foundation<br>import SwiftUI<br><br>// 1. We add Identifiable and Hashable to the Route. <br>// For sheets, the framework uses the &#39;id&#39; to track which item is presented.<br>enum ExampleRoute: Hashable, Identifiable {<br>    case example2<br>    case example3(id: String)<br><br>    var id: Self { self }<br>}<br><br>@MainActor<br>struct ExampleViewCoordinatorImpl: ExampleViewCoordinator, NavigationCoordination, SheetCoordination {<br>    <br>    let router: NavigationRouter<br>    // We initialize a SheetRouter specifically for our ExampleRoute<br>    let sheetRouter = SheetRouter&lt;ExampleRoute&gt;()<br>    <br>    init(router: NavigationRouter) {<br>        self.router = router<br>    }<br>    <br>    // Push navigation (Stack)<br>    func showExample2() {<br>        push(route: .example2)<br>    }<br><br>    // Modal presentation (Sheet)<br>    func showExample3(_ id: String) {<br>        present(.example3(id: id))<br>    }<br><br>    @ViewBuilder<br>    func build(_ route: ExampleRoute) -&gt; some View {<br>        switch route {<br>        case .example2:<br>            // Standard stack push assembly<br>            let nextCoordinator = Example2Coordinator(router: router)<br>            let nextViewModel = Example2ViewModel(coordinator: nextCoordinator)<br>            Example2View(viewModel: nextViewModel, coordinator: nextCoordinator)<br>            <br>        case .example3(let id):<br>            // We use the &#39;buildSheetNavigation&#39; helper. <br>            // This sets up a new NavigationStack inside the sheet,<br>            // allowing the modal to have its own internal push/pop flow and dismiss the sheet.<br>            buildSheetNavigation { router, dismiss in<br>                   let nextCoordinator = Example3Coordinator(router: router, dismissAction: dismiss)<br>                   // We pass the parameter directly into the ViewModel&#39;s initializer<br>                   let nextViewModel = Example3ViewModel(itemId: id, coordinator: nextCoordinator)<br>            <br>                   Example3View(viewModel: nextViewModel, coordinator: nextCoordinator)<br>            }<br>        }<br>    }<br>}</pre><h4><strong>Why this approach scales</strong></h4><p>Notice the logic inside the .example3(let id) case.</p><ul><li><strong>Parameter Safety</strong>: The id is passed safely through the enum case and injected directly into the next ViewModel. There is no global &quot;selectedID&quot; state to manage or break.</li><li><strong>Encapsulation</strong>:The coordinator is the one that controls if the next view will be pushed or presented in a sheet,Example3View has no idea it was presented as a sheet from ExampleView. It just knows it has a ViewModel and a Coordinator.</li><li><strong>Maintainability</strong>: If you later decide that Example3 should be a full-screen push instead of a sheet, you only change present(...) to push(...) in the Coordinator. The View and ViewModel code remains <strong>exactly the same</strong>.</li></ul><p>This is the “magic” of the SMT approach: by being slightly more verbose in our setup, we gain total freedom in our execution.</p><h3><strong>Top-Level Navigation: Tab Coordination</strong></h3><p>So far, we have looked at moving between screens within a single flow. But how do we manage the high-level entry points of our application? Most professional apps utilize a TabView as their root container.<br>In a standard SwiftUI app, you might find a massive MainView with a hardcoded TabView. In the SMT approach, we use a coordinator for the TabView. This allows us to handle complex scenarios like deep linking from a push notification directly to a tab without polluting our UI code with selection logic.</p><h4><strong>1. Defining the Tab Routes</strong></h4><p>Our tabs are defined by a specialized enum. For TabCoordination to work, the route must be CaseIterable(so the view can loop through them) and Identifiable (so SwiftUI can track the selection).</p><pre>/// The top-level entry points of our Example Application.<br>enum ExampleTab: String, CaseIterable, Identifiable {<br>    case example1<br>    case example2<br>    case example3<br><br>    var id: String { rawValue }<br>    var title: String { rawValue.capitalized }<br><br>    var systemImage: String {<br>        switch self {<br>        case .example1: &quot;house&quot;<br>        case .example2: &quot;magnifyingglass&quot;<br>        case .example3: &quot;person&quot;<br>        }<br>    }<br>}</pre><h4><strong>2. The Root View: Dynamic Assembly</strong></h4><p>By using a Coordinator for our tabs, our AppRootView becomes incredibly lean. It doesn&#39;t need to know which views live in which tabs it simply asks the Coordinator to &quot;build&quot; whatever tab is currently being iterated.</p><pre>struct ExampleTabView&lt;Coordinator: TabCoordination&gt;: View {<br>    // The view owns the coordinator that manages the top-level state<br>    @State var coordinator: Coordinator<br><br>    var body: some View {<br>        // Bindable maps the TabView&#39;s selection directly to the TabRouter&#39;s activeTab<br>        TabView(selection: Bindable(coordinator.tabRouter).activeTab) {<br>            ForEach(Coordinator.Route.allCases) { tab in<br>                coordinator.build(tab)<br>            }<br>        }<br>    }<br>}</pre><h4><strong>3. The Implementation: ExampleTabCoordinator</strong></h4><p>The ExampleTabCoordinator is the &quot;Master Assembly Line.&quot; Its job is to initialize the various modules of your app and wrap them in the appropriate navigation containers. By using buildNavigation, we ensure that each tab has its own independent NavigationStack, preventing navigation state from leaking across tabs.</p><pre>@MainActor<br>final class ExampleTabCoordinator: TabCoordination {<br>    typealias Route = ExampleTab<br><br>    // The TabRouter manages the active selection state<br>    let tabRouter: TabRouter&lt;ExampleTab&gt; = .init(route: .example1)<br><br>    @ViewBuilder<br>    func build(_ tab: ExampleTab) -&gt; some View {<br>        switch tab {<br>        case .example1:<br>            // Assembly of the Example 1 Module<br>            buildNavigation { router in<br>                let coordinator = ExampleViewCoordinatorImpl(router: router)<br>                ExampleView(<br>                    viewModel: ExampleViewModelImpl(<br>                        coordinator: coordinator<br>                    ),<br>                    coordinator: coordinator<br>                )<br>            }<br>            .tag(ExampleTab.example1)<br>            .tabItem { buildLabel(tab) }<br>            <br>        case .example2:<br>            // Assembly of the Example 2 Module<br>            buildNavigation { router in<br>                let coordinator = Example2ViewCoordinatorImpl(router: router)<br>                Example2View(<br>                    viewModel: Example2ViewModelImpl(<br>                        coordinator: coordinator<br>                    ),<br>                    coordinator: coordinator<br>                )<br>            }<br>            .tag(ExampleTab.example2)<br>            .tabItem { buildLabel(tab) }<br>            <br>        case .example3:<br>            // Assembly of the Example 3 Module<br>            buildNavigation { router in<br>                let coordinator = Example3ViewCoordinatorImpl(router: router)<br>                Example3View(<br>                    viewModel: Example3ViewModelImpl(<br>                        coordinator: coordinator<br>                    ),<br>                    coordinator: coordinator<br>                )<br>            }<br>            .tag(ExampleTab.example3)<br>            .tabItem { buildLabel(tab) }<br>        }<br>    }<br><br>    @ViewBuilder<br>    private func buildLabel(_ tab: ExampleTab) -&gt; some View {<br>        Label(tab.title, systemImage: tab.systemImage)<br>    }<br>}</pre><h4><strong>Programmatic Tab Switching</strong></h4><p>A common requirement in professional apps is switching tabs programmatically for example, a button on the Example 1 screen that needs to jump the user to the Example 3 tab.<br>In our architecture, this is a first-class citizen. Because our framework provides a selectTab method on the TabCoordination protocol, we can expose this capability to our ViewModels via a localized protocol.</p><h4><strong>The Communication Contract</strong></h4><p>If a feature needs to trigger a tab switch, we simply add it to that specific feature&#39;s Coordinator protocol:</p><pre>// ExampleViewModel.swift<br><br>protocol ExampleViewCoordinator {<br>    func showExample2()<br>    // Capability requested by business logic to switch tabs<br>    func jumpToExample3() <br>}</pre><h4><strong>The Implementation</strong></h4><p>The ExampleTabCoordinator can then leverage the framework&#39;s built-in capability to update the state. The TabRouter updates its activeTab property, and SwiftUI’s TabView updates the UI automatically.</p><pre>extension ExampleTabCoordinator: ExampleViewCoordinator {<br>    func jumpToExample3() {<br>        selectTab(.example3)<br>    }<br>}</pre><h4><strong>Why this is the SMT Gold Standard</strong></h4><p>By abstracting the Tab bar into a Coordinator, you achieve total isolation between your app’s “Skeleton” and its “Features”:</p><ul><li><strong>Scalability (S)</strong>: You can reorder or add new tabs in one file without touching the internal code of any feature module.</li><li><strong>Maintainability (M)</strong>: Deep linking becomes trivial. You can programmatically manipulate the tabRouter from a centralized location to guide the user exactly where they need to go.</li><li><strong>Testability (T)</strong>: You can unit test the ExampleTabCoordinator to ensure that calling selectTab(.example3) correctly updates the router&#39;s state without needing to render a single pixel.</li></ul><h3><strong>The Final Frontier: Deep Linking with SMT</strong></h3><p>We have built a system where features are modular and navigation is decoupled. But there is one final test for any navigation architecture: Deep Linking.<br>Deep linking is often the “Achilles’ heel” of SwiftUI apps. When a user taps a push notification or a URL like example-app://example1/example3?id=12345, the app needs to reach deep into its hierarchy, switch tabs, reset stacks, and present specific data. In a standard app, this usually involves a mess of global boolean flags and DispatchQueue.main.asyncAfter hacks.<br>In the SMT framework, we treat a Deep Link as a recursive path of instructions. Each Coordinator handles what it knows and passes the &quot;tail&quot; of the URL to the next child in line.</p><h4><strong>1. The DeepLinkableCoordination Protocol</strong></h4><p>To enable this, our framework provides a specialized protocol. It uses an inout array of strings, representing the path segments of a URL.</p><pre>public protocol DeepLinkableCoordination {<br>    /// Attempts to handle a deep-link represented as a mutable array of path segments.<br>    ///<br>    /// - Parameter path: The remaining path segments. <br>    ///   The coordinator removes segments it consumes so children receive the rest.<br>    @discardableResult<br>    func handle(deepLink path: inout [String]) -&gt; Bool<br>}</pre><h4><strong>2. The Entry Point: ExampleTabView</strong></h4><p>The Deep Link must enter the app somewhere. The best place is usually your root view (the Tab View), as it is always “alive” and can propagate the link down to the active features.</p><pre>struct ExampleTabView&lt;Coordinator: TabCoordination &amp; DeepLinkableCoordination&gt;: View {<br>    @State var coordinator: Coordinator<br><br>    var body: some View {<br>        TabView(selection: Bindable(coordinator.tabRouter).activeTab) {<br>            ForEach(Coordinator.Route.allCases) { tab in<br>                coordinator.build(tab)<br>            }<br>        }<br>        .onOpenURL(coordinator: coordinator, schema: &quot;example-app&quot;)<br>    }<br>}</pre><h4><strong>3. Managing Coordinator Lifecycles</strong></h4><p>For deep linking to be reliable, we need a slight adjustment to our ExampleTabCoordinator. Instead of initializing child coordinators inside the build method (which creates a new instance every time), we should hold them as properties.<br>This ensures that when we tell the exampleCoordinator to handle a link, we are talking to the same instance that is currently displayed on the screen.</p><p>We also implement the handle method. Think of this as a relay race: the Tab Coordinator grabs the first segment, switches the tab, and hands the baton to the child.</p><pre>@MainActor<br>struct ExampleTabCoordinator: TabCoordination {<br>    // We hold stable references to child coordinators to handle deep links predictably<br>    private let example1Coordinator = ExampleViewCoordinatorImpl(router: NavigationRouter())<br>    private let example2Coordinator = Example2ViewCoordinatorImpl(router: NavigationRouter())<br>    private let example3Coordinator = Example3ViewCoordinatorImpl(router: NavigationRouter())<br><br>    let tabRouter: TabRouter&lt;ExampleTab&gt; = .init(route: .example1)<br><br>    @ViewBuilder<br>    func build(_ tab: ExampleTab) -&gt; some View {<br>        switch tab {<br>        case .example1:<br>            buildNavigation(router: example1Coordinator.router) { _ in<br>                ExampleView(viewModel: ExampleViewModelImpl(coordinator: example1Coordinator), <br>                            coordinator: example1Coordinator)<br>            }<br>            .tag(ExampleTab.example1)<br>            .tabItem { Label(&quot;Home&quot;, systemImage: &quot;house&quot;) }<br>            <br>        case .example2:<br>            // ... similar assembly for Example 2<br>        case .example3:<br>            // ... similar assembly for Example 3<br>        }<br>    }<br>}<br><br>extension ExampleTabCoordinator: DeepLinkableCoordination {<br>    @discardableResult<br>    func handle(deepLink path: inout [String]) -&gt; Bool {<br>        guard !path.isEmpty else { return false }<br>        <br>        // Remove the first part of the path (e.g., &quot;example1&quot;)<br>        let tabComponent = path.removeFirst()<br>        <br>        switch tabComponent {<br>        case &quot;example1&quot;:<br>            self.selectTab(.example1)<br>            // Reset the stack to ensure we start from a clean state<br>            self.example1Coordinator.popToRoot()<br>            // Pass the REMAINING segments (the tail) to the child coordinator<br>            return self.example1Coordinator.handle(deepLink: &amp;path)<br>            <br>        case &quot;example2&quot;:<br>            self.selectTab(.example2)<br>            return self.example2Coordinator.handle(deepLink: &amp;path)<br>            <br>        default:<br>            return false // Unknown path<br>        }<br>    }<br>}</pre><pre>extension ExampleTabCoordinator: DeepLinkableCoordination {<br>    @discardableResult<br>    func handle(deepLink path: inout [String]) -&gt; Bool {<br>        guard !path.isEmpty else { return false }<br>        <br>        // Remove the first part of the path (e.g., &quot;example1&quot;)<br>        let tabComponent = path.removeFirst()<br>        <br>        switch tabComponent {<br>        case &quot;example1&quot;:<br>            self.selectTab(.example1)<br>            // Reset the stack to ensure we start from a clean state<br>            self.example1Coordinator.popToRoot()<br>            // Pass the REMAINING segments (the tail) to the child coordinator<br>            return self.example1Coordinator.handle(deepLink: &amp;path)<br>            <br>        case &quot;example2&quot;:<br>            self.selectTab(.example2)<br>            return self.example2Coordinator.handle(deepLink: &amp;path)<br>            <br>        default:<br>            return false // Unknown path<br>        }<br>    }<br>}</pre><h4><strong>Anatomy of a Deep Link: A Practical Example</strong></h4><p>Let’s trace a link: example-app://example1/example3?id=12345</p><ol><li><strong>The Entry Point</strong>: ExampleTabView receives the URL. It strips the scheme and passes [&quot;example1&quot;, &quot;example3?id=12345&quot;] to the ExampleTabCoordinator.</li><li><strong>The Tab Level</strong>: The Tab Coordinator sees &quot;example1&quot;. It switches the UI to the first tab and calls popToRoot() so the user doesn&#39;t get lost. It then takes the remaining array [&quot;example3?id=12345&quot;]and hands it to example1Coordinator.</li><li><strong>The Feature Level</strong>: example1Coordinator sees &quot;example3?id=12345&quot;. It parses the ID and calls its own present(.example3(id: &quot;12345&quot;)) logic.</li></ol><p><strong>Why this is the SMT Secret Weapon</strong></p><ul><li><strong>Scalability (S)</strong>: You can add 50 new routes, and the logic remains clean. You just follow the breadcrumbs.</li><li><strong>Maintainability (M)</strong>: The deep link follows the <strong>exact same structure</strong> as a manual touch. If the manual navigation works, the deep link works.</li><li><strong>Testability (T)</strong>: Since handle(deepLink:) is just a function that manipulates an array and calls other functions, you can unit test your entire deep-linking logic without ever launching a simulator.</li></ul><h3><strong>Wrapping Up Part 3</strong></h3><p>We have completed the “Logic Engine.” We now have a system where:</p><ul><li><strong>Views</strong> are generic and capability-driven.</li><li><strong>ViewModels</strong> are logic-pure and navigation-blind.</li><li><strong>Coordinators</strong> handle the assembly, the traffic, and the deep links.</li></ul><p>By following this modular coordination pattern, your app isn’t just a collection of screens — it’s a flexible, navigable system that can handle any requirement your business throws at it.<br>Next up in <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-visual-language-atomic-design-composability-part-4-e747a8f7a132">Part 4</a>: The Visual Language. We will finally touch the UI, looking at Atomic Design and how to build components that are as scalable as our logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a97ed114b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SMT Manifesto: The Logic Engine — MVVM+C (Part 2)]]></title>
            <link>https://medium.com/@goncalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26?source=rss-5800301374f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/17885b2f5e26</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gonçalo Frade]]></dc:creator>
            <pubDate>Mon, 04 May 2026 21:12:51 GMT</pubDate>
            <atom:updated>2026-05-06T08:19:06.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4KeFQpisM4H25VYM5fF8w.png" /></figure><p>In <a href="https://medium.com/@gonalofrade/the-smt-manifesto-mastering-architectural-foundations-in-swiftui-part-1-9332f61587b1">Part 1</a>, we laid the “bones” of our application. we talked about Modularization, the Domain Layer as our source of truth, the power of Use Cases, and how to glue it all together using Factory for Dependency Injection.<br>If <a href="https://medium.com/@gonalofrade/the-smt-manifesto-mastering-architectural-foundations-in-swiftui-part-1-9332f61587b1">Part 1</a> was the skeleton, Part 2 is the nervous system. We’re moving from the macro architecture to the micro logic that drives your UI.</p><h3><strong>The MVVM+C Triad</strong></h3><p>To maintain our SMT standards (Scalability, Maintainability, Testability), we use a refined version of the Model-View-ViewModel + Coordinator pattern that is adapted to SMT. Lets break down the responsibilities of MVVM+C:</p><ul><li><strong>The View:</strong> A “dumb” visual representation. It observes state and relays user intentions. It doesn’t decide <em>what</em>happens; it just reports that a button was tapped.</li><li><strong>The ViewModel:</strong> The brain. It handles business logic, transforms Domain models into UI-ready state, and communicates with Use Cases.</li><li><strong>The Coordinator:</strong> The traffic controller. It handles navigation and dependencies. By removing navigation logic from the View, we ensure that a View can be reused anywhere in the app without being “married” to its neighbor.</li></ul><blockquote><strong>Note:</strong> We are going to focus on the View and ViewModel marriage today. We will dive deep into the Coordinator’s implementation in <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5">Part 3</a>.</blockquote><h3><strong>The Decoupled Engine</strong></h3><p>Standard MVVM tutorials often have you hard-code a ViewModel into a View. Instead, we use Protocols to define the contract and Generics to allow the View to accept <em>any</em> object that fulfills that contract.</p><h4><strong>1. Defining the State</strong></h4><p>I prefer keeping the View State in a separate file (only if really needed). This makes the ViewModel much easier to read and allows the View to switch its entire layout based on a single enum.</p><pre>// ExampleViewState.swift<br>import Foundation<br><br>enum ExampleViewState {<br>    case loading<br>    case loaded(message: String)<br>    case error(errorMessage: String)<br>}</pre><h4><strong>2. The View Contract (Protocol)</strong></h4><p>We define a protocol to ensure the View knows exactly what it can access, without knowing <em>who</em> is providing it.</p><pre>// ExampleView.swift<br>import SwiftUI<br><br>@MainActor<br>protocol ExampleViewModel: Observable {<br>    var exampleState: ExampleViewState { get }<br>    var exampleVar2: Int { get set }<br>    func showExample2Screen()<br>    func loadData() async<br>}<br><br>struct ExampleView&lt;ViewModel: ExampleViewModel&gt;: View {<br>    @State private var viewModel: ViewModel<br><br>    init(viewModel: ViewModel) {<br>        self.viewModel = viewModel<br>    }<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            switch viewModel.exampleState {<br>            case .loading:<br>                ProgressView(&quot;Fetching data...&quot;)<br>            case .loaded(let message):<br>                Text(message)<br>                    .font(.headline)<br>            case .error(let error):<br>                Text(&quot;Error: \(error)&quot;)<br>                    .foregroundColor(.red)<br>            }<br><br>            Divider()<br><br>            Stepper(&quot;Counter: \(viewModel.exampleVar2)&quot;, value: $viewModel.exampleVar2)<br><br>            Button(&quot;Navigate to Screen 2&quot;) {<br>                viewModel.showExample2Screen()<br>            }<br>            .buttonStyle(.borderedProminent)<br>        }<br>        .padding()<br>        .task {<br>            await viewModel.loadData()<br>        }<br>    }<br>}</pre><h4><strong>3. The Implementation (ViewModel)</strong></h4><p>Here, we use our @Inject property wrappers from <a href="https://medium.com/@gonalofrade/the-smt-manifesto-mastering-architectural-foundations-in-swiftui-part-1-9332f61587b1">Part 1</a>. Notice how the ViewModel focuses on <em>logic</em> and <em>state coordination</em>.</p><pre>// ExampleViewModel.swift<br>import Foundation<br>import Factory<br>import Observation<br><br>@MainActor<br>@Observable<br>final class ExampleViewModelImpl: ExampleViewModel {<br>    @Inject(Container.exampleService) private var service<br>    @Inject(Container.exampleUseCase) private var useCase<br><br>    var exampleState: ExampleViewState = .loading<br>    var exampleVar2: Int = 0<br>    <br>    func loadData() async {<br>        // Simulate a network call or UseCase execution<br>        try? await Task.sleep(for: .seconds(2))<br>        exampleState = .loaded(message: &quot;SMT Architecture is Live!&quot;)<br>    }<br><br>    func showExample2Screen() {<br>        // This logic will be handled by the Coordinator in Part 3<br>        print(&quot;Routing to Screen 2...&quot;)<br>    } <br>}</pre><h3><strong>Previews: The Interactive Documentation for Your Team</strong></h3><p>In a professional environment, SwiftUI Previews are more than just a convenience for the person writing the code they are a living, interactive documentation. By using the protocol-based approach we’ve established, you turn your View files into a “visual catalog” that communicates exactly how the UI behaves in every possible scenario.</p><h4><strong>Communicating Through States</strong></h4><p>When a colleague opens your View, they shouldn’t have to dig through business logic or trigger a network call to see the “Error” state. They should simply look at the Canvas. By providing multiple #Preview blocks, you are providing an immediate reference for:</p><ul><li><strong>The Happy Path</strong>: What the user sees when everything works.</li><li><strong>Edge Cases</strong>: Empty states, extremely long text, or weird data formats.</li><li><strong>Error/Loading</strong>: The specific visual feedback for system failures or latency.</li></ul><p><strong>The Implementation</strong><br>Since our ExampleView only cares about the ExampleViewModel protocol, we can use a simple mock to provide &quot;Interactive Documentation&quot; for our team:</p><pre>// MARK: - Interactive Documentation (Previews)<br><br>private class MockExampleViewModel: ExampleViewModel {<br>    var exampleState: ExampleViewState<br>    var exampleVar2: Int = 0<br>    <br>    init(state: ExampleViewState) {<br>        self.exampleState = state<br>    }<br>    <br>    func showExample2Screen() { print(&quot;Navigating...&quot;) }<br>    func loadData() async { /* No-op for previews */ }<br>}<br><br>#Preview(&quot;Loading State&quot;) {<br>    ExampleView(viewModel: MockExampleViewModel(state: .loading))<br>}<br><br>#Preview(&quot;Loaded State (Short Content)&quot;) {<br>    ExampleView(viewModel: MockExampleViewModel(state: .loaded(&quot;Hello SMT!&quot;)))<br>}<br><br>#Preview(&quot;Loaded State (Long Content)&quot;) {<br>    ExampleView(viewModel: MockExampleViewModel(state: .loaded(&quot;This is a very long message to test how the UI handles text wrapping in a professional layout.&quot;)))<br>}<br><br>#Preview(&quot;Error State&quot;) {<br>    ExampleView(viewModel: MockExampleViewModel(state: .error(&quot;Could not connect to the SMT Server.&quot;)))<br>}</pre><h4><strong>Why This Matters for the Team</strong></h4><ul><li><strong>Design Verification</strong>: Your designers can see how the UI looks with real (or extreme) data without needing a staging environment.</li><li><strong>Onboarding</strong>: A new developer joining the team can see all the states of a feature just by scrolling through the Preview canvas.</li><li><strong>Efficiency</strong>: No more “How do I trigger the error state to fix a bug?” questions. The answer is already in the Previews.</li></ul><p>By treating Previews as a deliverable, you enhance the Maintainability of the project. You aren’t just shipping code, you’re shipping a clear, visual explanation of how that code is intended to work.</p><h3><strong>Why This Wins: The SMT Benefits</strong></h3><p>By taking this “extra” step with protocols and generics, you satisfy the SMT pillars in a way that standard SwiftUI tutorials simply cannot:</p><ol><li><strong>Testability (T) — #Previews on Steroids</strong>: You can create a MockExampleViewModel in seconds, allowing your team to verify every state instantly. <strong>A huge plus?</strong> Because the View is decoupled, you can easily ask an AI to generate dozens of Preview variations without it needing to navigate or understand overly complex business logic.</li><li><strong>Testability (T) — Reliable Snapshot Testing</strong>: Accuracy is king when “photographing” your UI. With this approach, you don’t have to fiddle with complex dependencies, mock servers, or environmental setups just to reach the exact visual state you need to verify. You simply pass the mock, set the state, and snap the shot.</li><li><strong>Testability (T) — Pure Unit Testing</strong>: You can test the ExampleViewModelImpl in total isolation. Since it depends on protocols (injected via Factory), you can swap real services for mocks and verify that your business logic handles every edge case with 100% predictability.</li><li><strong>Scalability (S) &amp; Maintainability (M) — Architectural Versatility</strong>: Decoupling the business logic from the View opens the door to high-level strategies that are usually a nightmare to implement:<br>• <strong>A/B Testing</strong>: Swap out ViewModels to test different business logic versions for different user segments without changing a single line of UI code.<br>• <strong>Feature Flagging</strong>: Toggle between “Legacy” and “Modern” logic flows seamlessly by injecting different implementations based on remote configuration.<br>• <strong>Platform-Specific Logic</strong>: Reuse the same View across iOS, iPadOS, and visionOS while injecting specialized ViewModels that handle different hardware capabilities or data constraints.</li></ol><h3><strong>Wrapping Up Part 2</strong></h3><p>We’ve decoupled the brain from the body. Our View is now a clean, generic wrapper that can be driven by any implementation of our protocol. This is the essence of Maintainability.<br>But how does this View get onto the screen? And who decides where the user goes next?<br>Next up in <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5">Part 3</a>: The Coordinator Layer, the final piece of the logic puzzle that handles navigation and assembly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17885b2f5e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The (S)calability (M)aintainability (T)estability Manifesto: Mastering Architectural Foundations in…]]></title>
            <link>https://medium.com/@goncalofrade/the-smt-manifesto-mastering-architectural-foundations-in-swiftui-part-1-9332f61587b1?source=rss-5800301374f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9332f61587b1</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gonçalo Frade]]></dc:creator>
            <pubDate>Mon, 04 May 2026 21:11:02 GMT</pubDate>
            <atom:updated>2026-05-07T09:51:52.590Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The (S)calability (M)</strong>aintainability (T)estability <strong>Manifesto: Mastering Architectural Foundations in SwiftUI (Part 1)</strong></h3><h3>S calability<br>M aintainability<br>T estability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BegNc0YDs0Y4IOXaOGS1Pw.png" /></figure><p>So, you’re starting a new project. Whether you’re building from the ground up or refactoring a legacy app, the goal is the same: Build it correctly from ground up, don’t let it become a “Spaghetti” mess where everything is tightly coupled and impossible to change.</p><h4><strong>Principles Over Patterns</strong></h4><p>This is an opinionated series based on hard-earned experience. <br>However, it is important to understand that SMT is a mindset, not a single rigid pattern. You can absolutely achieve SMT using other architectures like MVP, MVC, or TCA. You can (and should) make choices that diverge from this implementation as your project needs and evolves. Perhaps your team prefers a different coordination pattern than the one shared here, or you decide that Atomic Design doesn’t fit your visual workflow, or you have specific opinions on how to structure your test suites.</p><p>The specific “how” matters less than the “why.” This article is an implementation of a proven way to achieve this goal, but it is by no means the only way. As long as you adhere to the pillars of SMT which are built upon the modern industry standards of SOLID principles and Clean Architecture you are on the right path. Ultimately, these architectural choices exist for one reason: to enhance the productivity of your team and the stability of your codebase, allowing you to hit the market faster with significantly higher quality.</p><h4><strong>The Three Non-Negotiable Pillars</strong></h4><p>To build code that lasts, we need to follow a framework. I call it the SMT Approach, built on three non-negotiable pillars:</p><ul><li><strong>Scalability:</strong> The ability to expand the codebase, feature set, and team size without hitting a plateau in productivity. A scalable architecture ensures that adding the 100th feature is as seamless as the 1st, preventing exponential increases in build times, merge conflicts, and cognitive load.</li><li><strong>Maintainability:</strong> The measure of how easily code can be understood, repaired, or evolved. It is the art of localizing change, a maintainable system allows you to refactor business logic or swap out a major dependency like a network layer or a database with surgical precision and zero regressions.</li><li><strong>Testability:</strong> The structural design that allows you to verify every piece of business logic in isolation, giving you the confidence that a change in one module won’t break another.</li></ul><p>In this 5 parts article, we aren’t touching fancy animations. We are focusing strictly on the Foundations and Modularization the “rules” of your application that make SMT possible.</p><h3><strong>The Roadmap</strong></h3><p>Over the next four articles, we will cover:</p><ol><li><strong>The Blueprint:</strong> Modularization, Clean Layers, and Dependency Injection.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26"><strong>The Logic Engine:</strong> MVVM+C</a>.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-traffic-controller-mastering-swiftui-coordination-part-3-72a97ed114b5"><strong>The Traffic Controller:</strong> Mastering SwiftUI Coordination</a>.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-visual-language-atomic-design-composability-part-4-e747a8f7a132"><strong>The Visual Language:</strong> UI Composability and Atomic Design</a>.</li><li><a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-safety-net-absolute-confidence-through-testing-part-5-fd818bc8d924"><strong>The Safety Net:</strong> A complete testing strategy (Unit, UI, and Snapshots)</a>.</li></ol><h3><strong>The Project Structure: Organizing for SMT</strong></h3><p>Foundational architecture starts with the file system. We organize our layers into specific folders to enforce strict boundaries. This is the blueprint that enables your team to work in parallel without stepping on each other’s toes.</p><ul><li><strong>Domain</strong></li><li><strong>UseCases</strong></li><li><strong>Modules</strong> (Feature1, Feature2, Main, etc.)</li><li><strong>UI</strong> (Atoms, Molecules, Organisms)</li></ul><blockquote><strong>Note:</strong> While a typical app might have “Services” or “Repositories,” those are implementation details. We are focusing on the <strong>foundations</strong>. You can add specific layers as your app’s complexity grows.</blockquote><h4><strong>1. Domain: The Source of Truth</strong></h4><p>The Domain layer is the heart of your app. It holds the contracts (structs and protocols) highly tailored for your business needs. This layer has little-to-no logic, it is the pure definition of your app’s internal API.</p><blockquote><strong>The Golden Rule of Model Mapping:</strong></blockquote><blockquote>If you have a Service layer (API) or a Database layer (CoreData/SwiftData), those models (e.g., Codable or NSManagedObject) must never leave their respective scopes. <strong>You must always map these external models to your Domain models</strong>. Follow this strictly, and you can switch your network provider or your database engine without major refactors.</blockquote><h4><strong>2. Use Cases: The Logic Holders</strong></h4><p>Use Cases are the stateless “brains” of your app. If you find yourself repeating business logic across multiple ViewModels, you probably would be better with a Use Case. These are stateless, highly testable, “straight-to-the-point” objects. In most cases, they are simple structs with a single execution function.</p><pre>// MARK: - Domain Layer (Contract)<br>protocol CheckEligibilityForPromotionUseCase {<br>    func execute(user: User, trip: Trip) -&gt; Bool<br>}<br><br>// MARK: - UseCase Layer (Implementation)<br>struct CheckEligibilityForPromotionUseCaseImpl: CheckEligibilityForPromotionUseCase {<br>    <br>    // Business rules are encapsulated here, away from the UI.<br>    func execute(user: User, trip: Trip) -&gt; Bool {<br>        let isPremiumUser = user.membership == .gold || user.membership == .platinum<br>        let isLongDistanceTrip = trip.distance &gt; 500<br>        let hasRecentCancellations = user.cancellationHistory.contains { $0.date &gt; .oneMonthAgo }<br>        <br>        // The business &quot;Rule&quot;: Premium users get discounts on long trips <br>        // unless they have recent cancellations.<br>        return isPremiumUser &amp;&amp; isLongDistanceTrip &amp;&amp; !hasRecentCancellations<br>    }<br>}</pre><h4><strong>3. Modules: Feature Isolation</strong></h4><p>For an app to be Scalable, it must be modular. Each folder in the Modules directory represents a feature, and they must follow three strict rules:</p><ol><li><strong>Internal Domain:</strong> Modules can have internal models for logic that doesn’t need to be shared globally.</li><li><strong>No Direct Coupling:</strong> Modules only depend on the global Domain. To use a service, you must depend on its <em>protocol</em> defined in the Domain.</li><li><strong>The Coordinator Rule:</strong> Only a Coordinator can initialize another module.</li></ol><blockquote><strong>Future-Proofing with Swift Packages (SPM)</strong></blockquote><blockquote>While folder-based modularization is enough for most codebases, larger projects or enterprise environments may require moving features into independent Swift Packages.<br>The beauty of the SMT approach is portability. Because we already enforce strict boundaries and depend only on the Domain layer, moving a feature folder into its own SPM package is often a simple “lift and shift” rather than a week-long refactoring nightmare. This architecture enables you to share features across different apps or codebases with minimal friction.</blockquote><h4>UI (Atomic design)</h4><p>In this article we will use Atomic Design, every Module has its own View, but these Views are just “connectors” to business logic. The actual UI components (the buttons, cards, and headers) live in the UI layer. By using Atomic Design, we create a library of reusable, composable components that ensure visual consistency across the entire app.</p><p>We will talk more about this later on the <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-visual-language-atomic-design-composability-part-4-e747a8f7a132">part 4</a>.</p><h3><strong>The Swift Pillars: POP &amp; Generics</strong></h3><p>Before we go forward, we must understand the swift language tools provided to us and two pillars that make this architecture very efficient: <strong>Protocol-Oriented Programming</strong> and <strong>Generics</strong>.</p><p>We will use this tools heavily in our favor.</p><h4><strong>Protocol-Oriented Programming (POP)</strong></h4><p>In Swift, we favor composition over inheritance. Instead of a massive BaseClass, we use protocols to define “capabilities.”</p><ul><li><strong>Decoupling:</strong> By depending on a protocol (e.g., UserServiceProtocol) instead of a concrete class (UserService), our Modules don&#39;t need to know <em>how</em> a service works, only <em>what</em> it does.</li><li><strong>Testability:</strong> Protocols allow us to swap the real implementation for a “Mock” or “Stub” during Unit Testing or SwiftUI Previews.</li></ul><p>By coding to protocols rather than classes or structs, we create a adaptable system. This is the “D” in SOLID (Dependency Inversion). It allows us to:</p><ul><li>Swap out a real Service for a Mock during tests.</li><li>Keep modules from knowing about each other’s internal workings.</li><li>Enable SwiftUI Previews to work instantly by providing “dummy” data through a protocol.</li></ul><h4><strong>Generics: Power with Type Safety</strong></h4><p>Generics allow us to write code that works with any type, while still maintaining the strict safety that Swift is known for. In a modular foundation, we use Generics to avoid code duplication in our data handling.</p><p>I cannot say this enough, use Generics, don&#39;t be afraid of using them.</p><pre>// Example: A generic Result wrapper for our Domain layer<br>// This allows any Use Case to return a standardized response format<br>struct DomainResponse&lt;T&gt; {<br>    let data: T<br>    let timestamp: Date<br>}<br><br>// A Protocol using an &#39;associatedtype&#39; (POP + Generics combined)<br>protocol Repository {<br>    associatedtype Entity<br>    func fetchAll() -&gt; [Entity]<br>}</pre><p>By using Generics, we ensure that our TripRepository returns [Trip] and our UserRepository returns [User], all while using the same underlying logic.</p><h3><strong>The Glue: Dependency Injection with Factory</strong></h3><p>Im of the opinion that <strong>the less or none third party frameworks the better</strong>.</p><p>But unfortunately, although SwiftUI provides a capable DI mechanism using `Environments`, its not very useful on a MVVM approach. You can create you own DI mechanism, BUT it adds to maintenance and testability. Sometimes is better to use the third party that is proven and tested for a critical part of your app.</p><h4><strong>Why Factory?</strong></h4><p>Instead of passing dependencies through every initializer (which leads to “Init-Hell”), Factory allows us to register our services and inject them where they are needed without losing the ability to swap them out for “Mocks” during testing.</p><h4><strong>Mastering Scopes in a Modular World</strong></h4><p>When working with Modules, the Scope of your dependency is everything. Factory provides several scopes that define how long an object lives:</p><ul><li><strong>.unique</strong>: (Default) A new instance is created and returned every time it’s requested. This is perfect for ViewModels or transient Use Cases to ensure no “stale” state is shared.</li><li><strong>.singleton</strong>: The instance is created once and shared by everyone for the lifetime of the app. Use this sparingly for things like a UserSession.</li><li><strong>.cached</strong>: The object persists until the cache is reset.</li><li><strong>.shared</strong>: A weak reference. The object exists as long as someone else holds a strong reference to it. When the last reference goes away, the instance is deallocated.</li><li><strong>.scope</strong>: Allows you to use custom defined scopes (like .session). This is powerful for managing dependencies that should only exist during a specific lifecycle, such as while a user is logged in.</li></ul><blockquote><strong>The Connection to Modules:</strong><br>In a modular architecture, your Domain layer often defines a protocol (e.g., AuthenticationService), but the implementation lives in a separate Service module. By using a Global Container, you can register the implementation in your Main module but inject it into FeatureA or FeatureB seamlessly.</blockquote><pre>extension Container {<br>    // Unique (Default): A new instance is created every time.<br>    // Use this for ViewModels or transient Use Cases to prevent stale state.<br>    var loginUseCase: Factory&lt;LoginUseCaseProtocol&gt; {<br>        self { LoginUseCaseImpl() }<br>    }<br><br>    // Singleton: Created once, shared by everyone.<br>    // WARNING: Singletons are often an anti-pattern. Use them sparingly <br>    // for truly global state like a NetworkMonitor.<br>    var networkService: Factory&lt;NetworkProviding&gt; { <br>        self { NetworkProvider() }.singleton<br>    }<br><br>    // Session: Persists until the session is reset (e.g., User Logout).<br>    var myService: Factory&lt;MyServiceType&gt; { <br>        self { MyService() }.scope(.session)<br>    }<br><br>    // Shared: A weak reference. Lives as long as someone else is holding it.<br>    var sharedService: Factory&lt;SharedServiceProtocol&gt; {<br>        self { SharedService() }.shared<br>    }<br>}</pre><h4><strong>Wrapping Up Part 1</strong></h4><p>We’ve laid the foundation: Modularize early, map your models, and use Scopes to manage lifecycle. These foundations are what separate a “demo app” from a professional, SMT-compliant system.</p><p>Next In <a href="https://medium.com/@gonalofrade/the-smt-manifesto-the-logic-engine-mvvm-c-part-2-17885b2f5e26">Part 2</a>, we’ll move into the Logic Engine, showing how to build a robust MVVM+C engine using the power of Generics and Coordinators.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9332f61587b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>