<?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"><channel><title><![CDATA[SwiftUI Central]]></title><description><![CDATA[Blog of Alexandre Alcuvilla, iOS developer
Exploring new ways to create modern apps
Using SwiftUI, Combine and Async/Await and respect best practices
TDD, Unit ]]></description><link>https://swiftuicentral.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1645221211608/Z_EYR_Fcu.png</url><title>SwiftUI Central</title><link>https://swiftuicentral.com</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 06 Nov 2026 22:17:43 GMT</lastBuildDate><atom:link href="https://swiftuicentral.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The Composition Root Pattern in SwiftUI Apps]]></title><description><![CDATA[Every article in this series has ended with the same instruction: wire everything at the Composition Root. We've used it as the place where…]]></description><link>https://swiftuicentral.com/the-composition-root-pattern-in-swiftui-apps</link><guid isPermaLink="true">https://swiftuicentral.com/the-composition-root-pattern-in-swiftui-apps</guid><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Mon, 29 Jun 2026 20:46:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/2a70a263-b8f6-4cf1-97c3-180c76b28685.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every article in this series has ended with the same instruction: <em>wire everything at the Composition Root</em>. We've used it as the place where <code>RemoteFeedRepository</code> meets <code>CachingFeedRepository</code>, where <code>UserNotificationScheduler</code> gets injected into <code>ReminderViewModel</code>, where Decorators stack on top of each other.</p>
<p>But we've never stopped to examine the Composition Root itself.</p>
<p>This article is about that. What is a Composition Root, why does it matter, how to structure it as your app grows, and what goes wrong when you don't have one.</p>
<hr />
<h2>What Is the Composition Root?</h2>
<p>The Composition Root is <strong>the single place in your application where you assemble the object graph</strong> — connecting all concrete types together.</p>
<p>Mark Seemann, who coined the term, defines it as: <em>"a (preferably) unique location in an application where modules are composed together."</em></p>
<p>In a SwiftUI app, the natural Composition Root is the <code>@main</code> struct. It's the entry point. It starts before any view is shown. It has no business logic of its own. It is the perfect place to wire everything together.</p>
<pre><code class="language-swift">@main
struct FeedApp: App {
    var body: some Scene {
        WindowGroup {
            // Everything is composed here — and only here
            FeedView(
                viewModel: FeedViewModel(
                    loadFeed: LoadFeedUseCase(
                        repository: CachingFeedRepository(
                            decoratee: RemoteFeedRepository(url: feedURL),
                            cache: CodableFeedStore(storeURL: storeURL)
                        )
                    )
                )
            )
        }
    }
}
</code></pre>
<p>One place. All concrete types. All wiring. Nowhere else.</p>
<hr />
<h2>What Goes Wrong Without One</h2>
<p>Without a Composition Root, composition happens <em>everywhere</em>. ViewModels instantiate their own dependencies. Views create their own ViewModels. Repositories reference shared singletons. The object graph is implicit, scattered, and impossible to test.</p>
<pre><code class="language-swift">// ❌ No Composition Root — composition scattered across the codebase

final class FeedViewModel: ObservableObject {
    // Creates its own dependency — hidden, untestable
    private let repository = RemoteFeedRepository(url: URL(string: "https://api.example.com/feed")!)
}

struct FeedView: View {
    // Creates its own ViewModel — impossible to inject a stub
    @StateObject private var viewModel = FeedViewModel()
}
</code></pre>
<p>Every class that instantiates its own dependencies is doing two jobs: its own job, and the job of the Composition Root. That's a SRP violation — and it means you can never test any of it in isolation.</p>
<hr />
<h2>Step 1 — Extracting the Composition Root into a Factory</h2>
<p>As the app grows, the <code>@main</code> struct becomes cluttered. Extract the wiring into a dedicated factory:</p>
<pre><code class="language-swift">// CompositionRoot/FeedUIComposer.swift
enum FeedUIComposer {

    static func feedViewController(feedURL: URL, storeURL: URL) -&gt; FeedView {
        let store = CodableFeedStore(storeURL: storeURL)
        let remoteRepository = RemoteFeedRepository(url: feedURL)
        let cachingRepository = CachingFeedRepository(
            decoratee: remoteRepository,
            cache: store
        )
        let useCase = LoadFeedUseCase(repository: cachingRepository)
        let viewModel = FeedViewModel(loadFeed: useCase)
        return FeedView(viewModel: viewModel)
    }
}
</code></pre>
<p>The <code>@main</code> struct becomes a clean delegation:</p>
<pre><code class="language-swift">@main
struct FeedApp: App {
    private let feedURL = URL(string: "https://api.example.com/feed")!
    private let storeURL = FileManager.default
        .urls(for: .cachesDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("feed.store")

    var body: some Scene {
        WindowGroup {
            FeedUIComposer.feedViewController(feedURL: feedURL, storeURL: storeURL)
        }
    }
}
</code></pre>
<p>The <code>FeedUIComposer</code> is the Composition Root for the feed feature. It knows about every concrete type in the feature. Nothing else does.</p>
<hr />
<h2>Step 2 — Handling Navigation at the Composition Root</h2>
<p>Navigation is a composition concern. A view should not know what screen comes next — it should tell a coordinator <em>what happened</em>, and the coordinator decides <em>where to go</em>.</p>
<p>Define the coordination interface in the Presentation layer:</p>
<pre><code class="language-swift">// Presentation/FeedCoordinator.swift
protocol FeedCoordinator {
    func showItemDetail(_ item: FeedItem)
}
</code></pre>
<p>Implement it at the Composition Root:</p>
<pre><code class="language-swift">// CompositionRoot/FeedCoordinatorImpl.swift
final class FeedCoordinatorImpl: FeedCoordinator {
    private let navigationPath: Binding&lt;NavigationPath&gt;

    init(navigationPath: Binding&lt;NavigationPath&gt;) {
        self.navigationPath = navigationPath
    }

    func showItemDetail(_ item: FeedItem) {
        navigationPath.wrappedValue.append(item)
    }
}
</code></pre>
<p>Wire it in the composer:</p>
<pre><code class="language-swift">enum FeedUIComposer {

    static func feedScene(
        feedURL: URL,
        storeURL: URL,
        navigationPath: Binding&lt;NavigationPath&gt;
    ) -&gt; some View {
        let coordinator = FeedCoordinatorImpl(navigationPath: navigationPath)
        let viewModel = FeedViewModel(
            loadFeed: LoadFeedUseCase(
                repository: CachingFeedRepository(
                    decoratee: RemoteFeedRepository(url: feedURL),
                    cache: CodableFeedStore(storeURL: storeURL)
                )
            ),
            coordinator: coordinator
        )
        return FeedView(viewModel: viewModel)
    }
}
</code></pre>
<p>The <code>FeedView</code> and <code>FeedViewModel</code> have no idea what <code>NavigationPath</code> is. Navigation is a plug-in, defined by a protocol and wired at the Composition Root.</p>
<hr />
<h2>Step 3 — Composing Multiple Features</h2>
<p>Real apps have multiple features. Each feature gets its own composer. The app-level Composition Root composes the composers:</p>
<pre><code class="language-swift">// CompositionRoot/AppComposer.swift
struct AppComposer: View {
    @State private var navigationPath = NavigationPath()

    private let feedURL = URL(string: "https://api.example.com/feed")!
    private let storeURL = FileManager.default
        .urls(for: .cachesDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("feed.store")

    var body: some View {
        NavigationStack(path: $navigationPath) {
            FeedUIComposer.feedScene(
                feedURL: feedURL,
                storeURL: storeURL,
                navigationPath: $navigationPath
            )
            .navigationDestination(for: FeedItem.self) { item in
                ItemDetailUIComposer.detailScene(item: item)
            }
        }
    }
}
</code></pre>
<p>Each feature's internal wiring is invisible to the others. The app-level composer only knows about the <em>entry point</em> of each feature — not its internals.</p>
<hr />
<h2>The Composition Root Is the Only Place That Can</h2>
<p>The Composition Root has a unique privilege: <strong>it is the only place allowed to reference concrete types from multiple layers simultaneously</strong>.</p>
<table>
<thead>
<tr>
<th>Allowed where</th>
<th>Domain layer</th>
<th>Data layer</th>
<th>Presentation layer</th>
<th>Composition Root</th>
</tr>
</thead>
<tbody><tr>
<td>Reference <code>FeedRepository</code> (protocol)</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td>Reference <code>RemoteFeedRepository</code> (concrete)</td>
<td>❌</td>
<td>✅</td>
<td>❌</td>
<td>✅</td>
</tr>
<tr>
<td>Reference <code>CachingFeedRepository</code> (concrete)</td>
<td>❌</td>
<td>✅</td>
<td>❌</td>
<td>✅</td>
</tr>
<tr>
<td>Reference <code>FeedViewModel</code> (concrete)</td>
<td>❌</td>
<td>❌</td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td>Instantiate and connect all of the above</td>
<td>❌</td>
<td>❌</td>
<td>❌</td>
<td>✅</td>
</tr>
</tbody></table>
<p>If you find yourself instantiating a <code>RemoteFeedRepository</code> inside a ViewModel, or creating a <code>FeedViewModel</code> inside another ViewModel, something has leaked out of the Composition Root. Bring it back.</p>
<hr />
<h2>Testing the Composition Root</h2>
<p>The Composition Root itself is hard to unit test — and that's fine. Its job is wiring, not logic. What you can test is that the object graph it produces <strong>behaves correctly end-to-end</strong>:</p>
<pre><code class="language-swift">final class FeedUIComposerIntegrationTests: XCTestCase {

    func test_feedScene_rendersLoadedItems() async throws {
        let items = [FeedItem(id: UUID(), title: "Article", imageURL: anyURL())]
        let store = InMemoryFeedStore(stubbedItems: items)

        let viewModel = FeedViewModel(
            loadFeed: LoadFeedUseCase(
                repository: CachingFeedRepository(
                    decoratee: AlwaysFailingRepository(),
                    cache: store
                )
            ),
            coordinator: NullCoordinator()
        )

        await viewModel.onAppear()

        XCTAssertEqual(viewModel.items, items)
    }

    private func anyURL() -&gt; URL { URL(string: "https://any-url.com")! }
}
</code></pre>
<p>Integration tests at the composition boundary verify the wiring produces the expected behaviour — without hitting a real network or real file system.</p>
<hr />
<h2>Everything Comes Together</h2>
<p>Looking back at the full series, the Composition Root is the thread connecting every pattern:</p>
<table>
<thead>
<tr>
<th>Pattern</th>
<th>What it contributes to the Composition Root</th>
</tr>
</thead>
<tbody><tr>
<td>Dependency Injection</td>
<td>All dependencies are injected — the Root is where they're created</td>
</tr>
<tr>
<td>Clean Architecture</td>
<td>The Root is the only place that references all three layers</td>
</tr>
<tr>
<td>Decorator Pattern</td>
<td>Decorators are stacked here — nowhere else</td>
</tr>
<tr>
<td>Single Responsibility</td>
<td>The Root's only job is composition — no business logic</td>
</tr>
<tr>
<td>TDD Cache Layer</td>
<td><code>CodableFeedStore</code> is instantiated here</td>
</tr>
<tr>
<td>Dependency Inversion</td>
<td>Concrete types implement protocols; the Root connects them</td>
</tr>
<tr>
<td>Snapshot Testing</td>
<td>Tests stub the graph the Root would produce</td>
</tr>
</tbody></table>
<p>Every principle and pattern ultimately serves the same goal: <strong>keep each module unaware of how it's assembled</strong>, so the Composition Root can assemble it any way the current context demands — production, tests, previews, or a different product entirely.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Without Composition Root</th>
<th>With Composition Root</th>
</tr>
</thead>
<tbody><tr>
<td>Object graph assembled everywhere</td>
<td>Assembled in exactly one place</td>
</tr>
<tr>
<td>Changing infrastructure touches many files</td>
<td>One file changes</td>
</tr>
<tr>
<td>Testing requires unwinding hidden dependencies</td>
<td>Inject any configuration from tests</td>
</tr>
<tr>
<td>Features coupled through shared singletons</td>
<td>Features communicate through protocols</td>
</tr>
<tr>
<td>Adding a Decorator requires touching business logic</td>
<td>Stack it at the Root, touch nothing else</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>The Composition Root is not a framework feature or a library — it's a discipline. One place, one job: assembling the object graph.</p>
<p>In SwiftUI:</p>
<ol>
<li><p>The <code>@main</code> <strong>struct</strong> is the natural Composition Root.</p>
</li>
<li><p>Extract feature wiring into a <strong>UIComposer</strong> per feature as the app grows.</p>
</li>
<li><p>Wire <strong>navigation</strong> through a coordinator protocol — implement it at the Root.</p>
</li>
<li><p>Compose <strong>multiple features</strong> by having the app-level Root combine feature-level Roots.</p>
</li>
<li><p><strong>Integration test</strong> the wiring by constructing the graph with controlled collaborators.</p>
</li>
</ol>
<p>A codebase with a clear Composition Root is a codebase where every module is independently testable, every infrastructure choice is replaceable, and every new feature is added by extension — not by modification.</p>
<p>That is the promise of every principle in this series, fulfilled in one place.</p>
]]></content:encoded></item><item><title><![CDATA[Snapshot Testing in SwiftUI: Catching Visual Regressions Automatically]]></title><description><![CDATA[Unit tests verify logic. UI tests verify user flows. But neither catches the moment a refactor silently shifts a layout, changes a font, or breaks a dark…]]></description><link>https://swiftuicentral.com/snapshot-testing-in-swiftui-catching-visual-regressions-automatically</link><guid isPermaLink="true">https://swiftuicentral.com/snapshot-testing-in-swiftui-catching-visual-regressions-automatically</guid><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Mon, 29 Jun 2026 20:46:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/444aeeaa-0dc0-4dee-ab10-38ade4614735.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Unit tests verify logic. UI tests verify user flows. But neither catches the moment a refactor silently shifts a layout, changes a font, or breaks a dark mode style.</p>
<p><strong>Snapshot testing</strong> fills that gap. On the first run, it captures a reference image of your view. On every subsequent run, it renders the view again and compares it pixel-by-pixel to the reference. If anything changed — a padding, a colour, a missing element — the test fails and shows you exactly what shifted.</p>
<p>This article shows how to integrate snapshot testing into a SwiftUI project using <a href="https://github.com/pointfreeco/swift-snapshot-testing">swift-snapshot-testing</a> by Point-Free, and how to apply it in a way that complements rather than duplicates your existing unit tests.</p>
<hr />
<h2>Setup</h2>
<p>Add the package to your project via Swift Package Manager:</p>
<pre><code class="language-plaintext">https://github.com/pointfreeco/swift-snapshot-testing
</code></pre>
<p>Add it to your <strong>test target only</strong> — it's a development tool, not a production dependency.</p>
<pre><code class="language-swift">// In your test file
import SnapshotTesting
import SwiftUI
import XCTest
</code></pre>
<hr />
<h2>Your First Snapshot Test</h2>
<p>Take the <code>FeedView</code> from the Clean Architecture article. Here is a minimal snapshot test:</p>
<pre><code class="language-swift">final class FeedViewSnapshotTests: XCTestCase {

    func test_feedView_loadingState() {
        let sut = FeedView(viewModel: FeedViewModel(loadFeed: LoadingStub()))
        assertSnapshot(of: UIHostingController(rootView: sut), as: .image(on: .iPhone13))
    }
}

private class LoadingStub: LoadFeedUseCase {
    func execute() async throws -&gt; [FeedItem] {
        // Never resolves — keeps the view in loading state
        try await Task.sleep(nanoseconds: .max)
        return []
    }
}
</code></pre>
<p>On the first run, the test <strong>records</strong> a reference image and passes unconditionally. The image is saved alongside your test file:</p>
<pre><code class="language-plaintext">__Snapshots__/FeedViewSnapshotTests/test_feedView_loadingState.1.png
</code></pre>
<p>Commit this file to version control. From this point on, any change to the view that alters its appearance will fail the test and produce a diff image showing exactly what changed.</p>
<hr />
<h2>Testing Multiple States</h2>
<p>A well-designed snapshot test suite covers every meaningful visual state of a view. For a feed screen, that means at least three:</p>
<pre><code class="language-swift">final class FeedViewSnapshotTests: XCTestCase {

    func test_loadingState() {
        let sut = makeSUT(state: .loading)
        assertSnapshot(of: sut, as: .image(on: .iPhone13))
    }

    func test_loadedState() {
        let sut = makeSUT(state: .loaded)
        assertSnapshot(of: sut, as: .image(on: .iPhone13))
    }

    func test_errorState() {
        let sut = makeSUT(state: .error)
        assertSnapshot(of: sut, as: .image(on: .iPhone13))
    }

    // MARK: - Helpers

    private func makeSUT(state: FeedState) -&gt; UIViewController {
        let viewModel = FeedViewModelStub(state: state)
        let view = FeedView(viewModel: viewModel)
        return UIHostingController(rootView: view)
    }
}
</code></pre>
<p>The <code>FeedViewModelStub</code> drives the view into a specific state synchronously — no async, no timers, no network:</p>
<pre><code class="language-swift">private enum FeedState { case loading, loaded, error }

@MainActor
private final class FeedViewModelStub: ObservableObject {
    @Published var items: [FeedItem] = []
    @Published var isLoading = false
    @Published var errorMessage: String?

    init(state: FeedState) {
        switch state {
        case .loading:
            isLoading = true
        case .loaded:
            items = [
                FeedItem(id: UUID(), title: "Test-Driven Development", imageURL: anyURL()),
                FeedItem(id: UUID(), title: "Clean Architecture", imageURL: anyURL()),
                FeedItem(id: UUID(), title: "SOLID Principles", imageURL: anyURL())
            ]
        case .error:
            errorMessage = "Could not load feed. Please try again."
        }
    }
}
</code></pre>
<p>Three tests, three reference images, every visual state covered.</p>
<hr />
<h2>Testing Dark Mode and Accessibility</h2>
<p>One of the most valuable uses of snapshot testing is catching appearance regressions across colour schemes and Dynamic Type sizes — issues that are easy to miss in manual testing.</p>
<pre><code class="language-swift">func test_loadedState_darkMode() {
    let sut = makeSUT(state: .loaded)
    sut.overrideUserInterfaceStyle = .dark
    assertSnapshot(of: sut, as: .image(on: .iPhone13))
}

func test_loadedState_largeTextSize() {
    let sut = makeSUT(state: .loaded)
    assertSnapshot(
        of: sut,
        as: .image(on: .iPhone13, traits: UITraitCollection(preferredContentSizeCategory: .accessibilityLarge))
    )
}
</code></pre>
<p>These tests run in under a second and catch broken contrast ratios, truncated labels, and overflowing layouts before they reach a user.</p>
<hr />
<h2>Snapshot Testing Respects Your Architecture</h2>
<p>Notice what we are <em>not</em> doing: we're not testing the ViewModel logic in snapshot tests. We already did that in unit tests. The <code>FeedViewModelStub</code> drives the view into a known state — it exists purely to support rendering.</p>
<p>This maps directly to the layered architecture from previous articles:</p>
<pre><code class="language-plaintext">Unit tests      → Domain (use cases, formatters, decorators)
Snapshot tests  → Presentation (views in each visual state)
Integration tests → Full stack (real use case, stubbed network)
</code></pre>
<p>Each layer of tests has a focused responsibility. Snapshot tests answer one question: <strong>does the view look right?</strong> They do not answer whether the data loading works, whether the cache strategy is correct, or whether navigation is wired up — those are answered elsewhere.</p>
<hr />
<h2>Updating Snapshots Intentionally</h2>
<p>When you make an intentional UI change — a new design, a revised layout — the snapshot test will fail because the reference no longer matches. This is correct behaviour. Update the reference by setting the <code>record</code> flag:</p>
<pre><code class="language-swift">// Temporarily set to record new snapshots
func test_loadedState() {
    let sut = makeSUT(state: .loaded)
    assertSnapshot(of: sut, as: .image(on: .iPhone13), record: true)
}
</code></pre>
<p>Run the test once, then remove the <code>record: true</code> flag and commit the new reference image. The test now guards the new appearance.</p>
<p>A common workflow: use a CI environment variable to control recording, so snapshots are never accidentally updated in a pipeline:</p>
<pre><code class="language-swift">let isRecording = ProcessInfo.processInfo.environment["RECORD_SNAPSHOTS"] == "true"
assertSnapshot(of: sut, as: .image(on: .iPhone13), record: isRecording)
</code></pre>
<hr />
<h2>Naming and Organising Snapshot Tests</h2>
<p>Reference images are stored next to the test file by default:</p>
<pre><code class="language-plaintext">FeedViewSnapshotTests.swift
__Snapshots__/
  FeedViewSnapshotTests/
    test_loadedState.1.png
    test_loadedState_darkMode.1.png
    test_loadedState_largeTextSize.1.png
    test_loadingState.1.png
    test_errorState.1.png
</code></pre>
<p>Keep test function names descriptive and consistent. They become the filenames of your reference images, which you review in code review like any other asset.</p>
<hr />
<h2>What Snapshot Testing Catches That Unit Tests Miss</h2>
<pre><code class="language-swift">// This unit test passes ✅
func test_errorState_setsErrorMessage() async {
    let (sut, _) = makeSUT(loadResult: .failure(anyError()))
    await sut.onAppear()
    XCTAssertNotNil(sut.errorMessage)
}

// But the snapshot test catches this ❌
// The error message label is white text on a white background —
// invisible to the user, but correct according to the unit test.
</code></pre>
<p>Unit tests verify <strong>values</strong>. Snapshot tests verify <strong>appearance</strong>. You need both.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Without Snapshot Tests</th>
<th>With Snapshot Tests</th>
</tr>
</thead>
<tbody><tr>
<td>Visual regressions discovered by QA or users</td>
<td>Caught on every CI run</td>
</tr>
<tr>
<td>Dark mode broken silently</td>
<td>Test fails with a diff image</td>
</tr>
<tr>
<td>Large text truncates labels unnoticed</td>
<td>Accessibility trait test catches it</td>
</tr>
<tr>
<td>Reviewing UI changes requires running the app</td>
<td>Review a PNG in the pull request</td>
</tr>
<tr>
<td>Refactors break layouts unexpectedly</td>
<td>Intentional changes require explicit snapshot update</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>Snapshot testing is the missing layer between unit tests and full UI automation. It answers the question unit tests cannot: <strong>does the view actually look right?</strong></p>
<p>In SwiftUI:</p>
<ol>
<li><p>Drive views into <strong>each meaningful visual state</strong> using a stub ViewModel — synchronously, with no infrastructure.</p>
</li>
<li><p>Capture a reference image for each state and commit it to version control.</p>
</li>
<li><p>Test <strong>across dimensions</strong>: light/dark mode, Dynamic Type sizes, different device sizes.</p>
</li>
<li><p>Update references <strong>intentionally</strong> — a failing snapshot is a signal that something visual changed, expected or not.</p>
</li>
<li><p>Keep snapshot tests focused on appearance. Let unit tests handle logic.</p>
</li>
</ol>
<p>Together, unit tests and snapshot tests form a safety net where logic regressions and visual regressions are each caught by the tool best suited to detect them.</p>
]]></content:encoded></item><item><title><![CDATA[Dependency Inversion in SwiftUI: Programming to Protocols]]></title><description><![CDATA[Of all the SOLID principles, the Dependency Inversion Principle (DIP) is the one that most directly enables testability and long-term flexibility. Yet it's…]]></description><link>https://swiftuicentral.com/dependency-inversion-in-swiftui-programming-to-protocols</link><guid isPermaLink="true">https://swiftuicentral.com/dependency-inversion-in-swiftui-programming-to-protocols</guid><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Mon, 29 Jun 2026 20:40:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/a04a0e80-45ba-4b9c-af5f-184332dad30f.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Of all the SOLID principles, the Dependency Inversion Principle (DIP) is the one that most directly enables testability and long-term flexibility. Yet it's also the most commonly misunderstood.</p>
<p>DIP states two things:</p>
<ol>
<li><p><strong>High-level modules should not depend on low-level modules.</strong> Both should depend on abstractions.</p>
</li>
<li><p><strong>Abstractions should not depend on details.</strong> Details should depend on abstractions.</p>
</li>
</ol>
<p>In plain terms: the parts of your app that contain business logic should never import or instantiate the parts that deal with infrastructure (network, disk, third-party SDKs). The dependency points the <em>other way</em> — toward an abstraction that both sides agree on.</p>
<p>This article shows what violating DIP looks like in SwiftUI, why it matters, and how to systematically invert the dependencies in a real feature.</p>
<hr />
<h2>The Problem: High-Level Code Depending on Low-Level Details</h2>
<p>Consider a notification feature. The ViewModel decides <em>when</em> to send a notification. A service decides <em>how</em> to send it. A common first pass looks like this:</p>
<pre><code class="language-swift">import UserNotifications  // ⚠️ Infrastructure import in a high-level module

@MainActor
final class ReminderViewModel: ObservableObject {
    @Published var isScheduled = false

    func scheduleReminder(title: String, in seconds: TimeInterval) async {
        let content = UNMutableNotificationContent()
        content.title = title
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: seconds,
            repeats: false
        )
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            trigger: trigger
        )

        do {
            try await UNUserNotificationCenter.current().add(request)
            isScheduled = true
        } catch {
            isScheduled = false
        }
    }
}
</code></pre>
<p>The ViewModel imports <code>UserNotifications</code> and instantiates <code>UNUserNotificationCenter</code> directly. The high-level business decision (<em>when</em> to schedule) is fused with the low-level delivery detail (<em>how</em> to schedule).</p>
<p>Consequences:</p>
<ul>
<li><p>You cannot test <code>scheduleReminder</code> without triggering real system notifications.</p>
</li>
<li><p>Swapping <code>UserNotifications</code> for a different delivery mechanism (push, in-app, analytics event) requires modifying the ViewModel.</p>
</li>
<li><p>The ViewModel accumulates knowledge it shouldn't have.</p>
</li>
</ul>
<hr />
<h2>Step 1 — Define an Abstraction Owned by the High-Level Module</h2>
<p>The key insight of DIP: <strong>the abstraction belongs to the high-level module, not the low-level one</strong>.</p>
<p>The ViewModel defines what it needs. The infrastructure provides it.</p>
<pre><code class="language-swift">// Domain/Notifications/NotificationScheduler.swift
protocol NotificationScheduler {
    func schedule(title: String, in seconds: TimeInterval) async throws
}
</code></pre>
<p>This protocol lives in the Domain layer. It expresses a business need in business language — no mention of <code>UNUserNotificationCenter</code>, <code>UNMutableNotificationContent</code>, or any framework type.</p>
<hr />
<h2>Step 2 — Invert the Dependency in the ViewModel</h2>
<p>The ViewModel now depends on the abstraction, not the concrete type:</p>
<pre><code class="language-swift">@MainActor
final class ReminderViewModel: ObservableObject {
    @Published private(set) var isScheduled = false

    private let scheduler: NotificationScheduler

    init(scheduler: NotificationScheduler) {
        self.scheduler = scheduler
    }

    func scheduleReminder(title: String, in seconds: TimeInterval) async {
        do {
            try await scheduler.schedule(title: title, in: seconds)
            isScheduled = true
        } catch {
            isScheduled = false
        }
    }
}
</code></pre>
<p>No framework imports. No concrete types. The ViewModel is now a pure business logic coordinator — it decides <em>when</em> and delegates <em>how</em> entirely to whoever implements <code>NotificationScheduler</code>.</p>
<hr />
<h2>Step 3 — Implement the Protocol in the Infrastructure Layer</h2>
<p>The concrete implementation lives in the Data/Infrastructure layer. It can import anything it needs without polluting the Domain or Presentation layers:</p>
<pre><code class="language-swift">// Infrastructure/Notifications/UserNotificationScheduler.swift
import UserNotifications

final class UserNotificationScheduler: NotificationScheduler {
    func schedule(title: String, in seconds: TimeInterval) async throws {
        let content = UNMutableNotificationContent()
        content.title = title
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: seconds,
            repeats: false
        )
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            trigger: trigger
        )

        try await UNUserNotificationCenter.current().add(request)
    }
}
</code></pre>
<p><code>UserNotifications</code> is now confined to a single, replaceable class. The rest of the codebase has no idea it exists.</p>
<hr />
<h2>Step 4 — Test the ViewModel Without Any Framework</h2>
<p>With the abstraction in place, testing is straightforward:</p>
<pre><code class="language-swift">final class ReminderViewModelTests: XCTestCase {

    func test_scheduleReminder_setsIsScheduledOnSuccess() async {
        let (sut, scheduler) = makeSUT()

        await sut.scheduleReminder(title: "Buy groceries", in: 3600)

        XCTAssertTrue(sut.isScheduled)
        XCTAssertEqual(scheduler.scheduledTitles, ["Buy groceries"])
    }

    func test_scheduleReminder_clearsIsScheduledOnFailure() async {
        let (sut, _) = makeSUT(schedulerResult: .failure(anyError()))

        await sut.scheduleReminder(title: "Any", in: 3600)

        XCTAssertFalse(sut.isScheduled)
    }

    func test_scheduleReminder_passesCorrectDuration() async {
        let (sut, scheduler) = makeSUT()

        await sut.scheduleReminder(title: "Standup", in: 900)

        XCTAssertEqual(scheduler.scheduledSeconds, [900])
    }

    // MARK: - Helpers

    private func makeSUT(
        schedulerResult: Result&lt;Void, Error&gt; = .success(())
    ) -&gt; (ReminderViewModel, NotificationSchedulerSpy) {
        let scheduler = NotificationSchedulerSpy(result: schedulerResult)
        let sut = ReminderViewModel(scheduler: scheduler)
        return (sut, scheduler)
    }

    private func anyError() -&gt; Error { NSError(domain: "test", code: 0) }
}

// MARK: - Test Double

private class NotificationSchedulerSpy: NotificationScheduler {
    private let result: Result&lt;Void, Error&gt;
    private(set) var scheduledTitles: [String] = []
    private(set) var scheduledSeconds: [TimeInterval] = []

    init(result: Result&lt;Void, Error&gt;) { self.result = result }

    func schedule(title: String, in seconds: TimeInterval) async throws {
        scheduledTitles.append(title)
        scheduledSeconds.append(seconds)
        try result.get()
    }
}
</code></pre>
<p>No <code>UserNotifications</code>. No simulator. No permission dialogs. The entire ViewModel is verified by fast, deterministic unit tests.</p>
<hr />
<h2>Recognising DIP Violations</h2>
<p>A DIP violation always looks like one of these patterns:</p>
<pre><code class="language-swift">// ❌ Importing infrastructure in a high-level module
import UserNotifications
import FirebaseAnalytics
import CoreData
import Alamofire

// ❌ Instantiating concrete types inside business logic
let service = UserNotificationScheduler()
let tracker = FirebaseAnalyticsTracker()
let store = CoreDataFeedStore()

// ❌ Using a singleton from a third-party framework
Analytics.shared.track(...)
URLSession.shared.data(from:...)
</code></pre>
<p>Each of these fuses a business decision with an infrastructure detail. Invert it by extracting a protocol at the boundary.</p>
<hr />
<h2>DIP Applied Across the Series</h2>
<p>Looking back at the articles in this series, DIP is present in every pattern we've used:</p>
<table>
<thead>
<tr>
<th>Article</th>
<th>Protocol (abstraction)</th>
<th>Concrete type (detail)</th>
</tr>
</thead>
<tbody><tr>
<td>Dependency Injection</td>
<td><code>FeedRepository</code></td>
<td><code>RemoteFeedRepository</code></td>
</tr>
<tr>
<td>Clean Architecture</td>
<td><code>FeedRepository</code></td>
<td><code>RemoteFeedRepository</code></td>
</tr>
<tr>
<td>Decorator Pattern</td>
<td><code>FeedRepository</code></td>
<td><code>CachingFeedRepository</code> wrapping <code>RemoteFeedRepository</code></td>
</tr>
<tr>
<td>SRP</td>
<td><code>LoadProfileUseCase</code></td>
<td><code>RemoteLoadProfileUseCase</code></td>
</tr>
<tr>
<td>TDD Cache Layer</td>
<td><code>FeedStore</code></td>
<td><code>CodableFeedStore</code></td>
</tr>
<tr>
<td><strong>This article</strong></td>
<td><code>NotificationScheduler</code></td>
<td><code>UserNotificationScheduler</code></td>
</tr>
</tbody></table>
<p>DIP is not a separate technique — it's the <strong>structural backbone</strong> that makes every other pattern composable, testable, and replaceable.</p>
<hr />
<h2>Wiring at the Composition Root</h2>
<pre><code class="language-swift">@main
struct ReminderApp: App {
    var body: some Scene {
        WindowGroup {
            ReminderView(
                viewModel: ReminderViewModel(
                    scheduler: UserNotificationScheduler()
                )
            )
        }
    }
}
</code></pre>
<p>The concrete type appears once, at the entry point. Everything else in the codebase works with the protocol.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Tight Coupling (no DIP)</th>
<th>Inverted Dependency (DIP)</th>
</tr>
</thead>
<tbody><tr>
<td>ViewModel imports <code>UserNotifications</code></td>
<td>ViewModel imports nothing</td>
</tr>
<tr>
<td>Changing delivery mechanism modifies business logic</td>
<td>Only the concrete class changes</td>
</tr>
<tr>
<td>Tests require real system APIs</td>
<td>Tests use a fast spy</td>
</tr>
<tr>
<td>Reusing the ViewModel in a different context is impossible</td>
<td>Drop in any conforming type</td>
</tr>
<tr>
<td>Third-party SDK updates ripple across the codebase</td>
<td>Impact contained to one class</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>The Dependency Inversion Principle is the practice of <strong>protecting business logic from infrastructure details</strong> by pointing all dependencies toward abstractions, never toward concretions.</p>
<p>In SwiftUI:</p>
<ol>
<li><p>Define a <strong>protocol</strong> in the Domain layer that expresses what the business needs, in business language.</p>
</li>
<li><p><strong>Inject</strong> that protocol into the ViewModel through the initialiser — no singletons, no direct instantiation.</p>
</li>
<li><p>Implement the protocol in the <strong>Infrastructure layer</strong>, where framework imports are confined.</p>
</li>
<li><p>Wire the concrete type at the <strong>Composition Root</strong> — the only place where all layers meet.</p>
</li>
<li><p>Test with a <strong>spy or stub</strong> — no framework, no side effects, no flakiness.</p>
</li>
</ol>
<p>Once your high-level modules depend only on protocols they own, infrastructure becomes a plug-in — swappable, mockable, and completely isolated from the logic that matters most.</p>
]]></content:encoded></item><item><title><![CDATA[Test-Driving a Cache Layer in SwiftUI ]]></title><description><![CDATA[In previous articles, we built a CachingFeedRepository by writing the implementation first and tests after. That works — but it leaves a subtle gap: the…]]></description><link>https://swiftuicentral.com/test-driving-a-cache-layer-in-swiftui</link><guid isPermaLink="true">https://swiftuicentral.com/test-driving-a-cache-layer-in-swiftui</guid><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Mon, 22 Jun 2026 21:27:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/b63478a6-98a6-4898-b725-acb397802d95.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In previous articles, we built a <code>CachingFeedRepository</code> by writing the implementation first and tests after. That works — but it leaves a subtle gap: the tests are shaped by the implementation you already wrote, not by the behaviour you actually need.</p>
<p><strong>Test-Driven Development</strong> (TDD) reverses the order. You write a failing test first, write just enough code to make it pass, then refactor. Each test specifies a new piece of behaviour. The implementation emerges from the tests, not the other way around.</p>
<p>This article builds a cache layer for a feed feature from scratch, using the TDD cycle: <strong>Red → Green → Refactor</strong>.</p>
<hr />
<h2>What We're Building</h2>
<p>A <code>FeedStore</code> that can:</p>
<ol>
<li><p>Save a list of feed items to disk.</p>
</li>
<li><p>Load the previously saved items.</p>
</li>
<li><p>Delete the cache.</p>
</li>
<li><p>Deliver an empty result when no cache exists.</p>
</li>
</ol>
<p>We'll implement this using the file system so the cache survives app restarts.</p>
<hr />
<h2>The Interface (Domain Layer)</h2>
<p>Before writing any test, define the interface in the Domain layer. This is the contract our store must fulfil:</p>
<pre><code class="language-swift">// Domain/Cache/FeedStore.swift
protocol FeedStore {
    func save(_ items: [FeedItem]) throws
    func load() throws -&gt; [FeedItem]
    func delete() throws
}
</code></pre>
<p>Now we write tests against this interface. The concrete type under test is <code>CodableFeedStore</code> — but our tests only ever reference <code>FeedStore</code>. This means we could swap the implementation for Core Data or SQLite without changing a single test.</p>
<hr />
<h2>Red — Write a Failing Test First</h2>
<p>Start with the simplest possible behaviour: <strong>loading from an empty store delivers an empty array</strong>.</p>
<pre><code class="language-swift">// DataTests/Cache/CodableFeedStoreTests.swift
final class CodableFeedStoreTests: XCTestCase {

    func test_load_deliversEmptyResultOnEmptyCache() throws {
        let sut = makeSUT()

        let result = try sut.load()

        XCTAssertEqual(result, [])
    }

    // MARK: - Helpers

    private func makeSUT(file: StaticString = #file, line: UInt = #line) -&gt; FeedStore {
        let storeURL = testSpecificStoreURL()
        let sut = CodableFeedStore(storeURL: storeURL)
        trackForMemoryLeaks(sut, file: file, line: line)
        return sut
    }

    private func testSpecificStoreURL() -&gt; URL {
        FileManager.default
            .urls(for: .cachesDirectory, in: .userDomainMask)[0]
            .appendingPathComponent("\(type(of: self)).store")
    }
}
</code></pre>
<p>Run the test. It doesn't compile — <code>CodableFeedStore</code> doesn't exist yet. That's the <strong>Red</strong> phase.</p>
<h3>Memory Leak Tracking</h3>
<p>A small helper that turns memory leaks into test failures:</p>
<pre><code class="language-swift">extension XCTestCase {
    func trackForMemoryLeaks(_ instance: AnyObject, file: StaticString = #file, line: UInt = #line) {
        addTeardownBlock { [weak instance] in
            XCTAssertNil(instance, "Instance should have been deallocated. Potential memory leak.", file: file, line: line)
        }
    }
}
</code></pre>
<p>This is a technique from Essential Developer: catch retain cycles at the test layer before they ever reach production.</p>
<hr />
<h2>Green — Write the Minimum Code to Pass</h2>
<p>Create the bare minimum <code>CodableFeedStore</code>:</p>
<pre><code class="language-swift">// Data/Cache/CodableFeedStore.swift
final class CodableFeedStore: FeedStore {
    private let storeURL: URL

    init(storeURL: URL) {
        self.storeURL = storeURL
    }

    func load() throws -&gt; [FeedItem] {
        guard let data = try? Data(contentsOf: storeURL) else {
            return []
        }
        return try JSONDecoder().decode([FeedItem].self, from: data)
    }

    func save(_ items: [FeedItem]) throws {
        // Implement later
        let data = try JSONEncoder().encode(items)
        try data.write(to: storeURL, options: .atomic)
    }

    func delete() throws {
        guard FileManager.default.fileExists(atPath: storeURL.path) else { return }
        try FileManager.default.removeItem(at: storeURL)
    }
}
</code></pre>
<p>Test passes. <strong>Green</strong>.</p>
<hr />
<h2>Refactor — Clean Up Before Moving On</h2>
<p>Before the next test, address one issue: <strong>test isolation</strong>. If the test writes to disk and crashes, the next run finds leftover data and may get a false positive or false negative.</p>
<p>Add <code>setUp</code> and <code>tearDown</code> to always start and end with a clean slate:</p>
<pre><code class="language-swift">override func setUp() {
    super.setUp()
    deleteStoreArtifacts()
}

override func tearDown() {
    super.tearDown()
    deleteStoreArtifacts()
}

private func deleteStoreArtifacts() {
    try? FileManager.default.removeItem(at: testSpecificStoreURL())
}
</code></pre>
<p>Each test now owns its own isolated store URL and cleans up after itself. <strong>Refactor done</strong>.</p>
<hr />
<h2>Red → Green → Refactor: Saving and Loading</h2>
<p>Next behaviour: <strong>saving items and loading them back delivers the same items</strong>.</p>
<pre><code class="language-swift">func test_load_deliversItemsPreviouslySaved() throws {
    let items = makeItems()
    let sut = makeSUT()

    try sut.save(items)
    let loaded = try sut.load()

    XCTAssertEqual(loaded, items)
}
</code></pre>
<p><strong>Red</strong> — run it. It passes immediately because <code>save</code> and <code>load</code> were already implemented. This is expected: we wrote the minimum implementation in the first Green phase. The test confirms the behaviour is correct.</p>
<p>Add a helper to keep tests readable:</p>
<pre><code class="language-swift">private func makeItems() -&gt; [FeedItem] {
    [
        FeedItem(id: UUID(), title: "First", imageURL: URL(string: "https://first.com")!),
        FeedItem(id: UUID(), title: "Second", imageURL: URL(string: "https://second.com")!)
    ]
}
</code></pre>
<hr />
<h2>Red → Green → Refactor: Override on Save</h2>
<p>Behaviour: <strong>saving twice delivers only the latest items</strong>.</p>
<pre><code class="language-swift">func test_load_deliversLastSavedItemsOnMultipleSaves() throws {
    let firstItems = makeItems()
    let latestItems = [FeedItem(id: UUID(), title: "Latest", imageURL: URL(string: "https://latest.com")!)]
    let sut = makeSUT()

    try sut.save(firstItems)
    try sut.save(latestItems)
    let loaded = try sut.load()

    XCTAssertEqual(loaded, latestItems)
}
</code></pre>
<p><strong>Green</strong> immediately — <code>.atomic</code> write overwrites the file. No code change needed.</p>
<hr />
<h2>Red → Green → Refactor: Deletion</h2>
<p>Behaviour: <strong>loading after deletion delivers an empty result</strong>.</p>
<pre><code class="language-swift">func test_load_deliversEmptyResultAfterDeletion() throws {
    let sut = makeSUT()

    try sut.save(makeItems())
    try sut.delete()
    let loaded = try sut.load()

    XCTAssertEqual(loaded, [])
}
</code></pre>
<p><strong>Green</strong> — <code>delete()</code> removes the file, and <code>load()</code> returns <code>[]</code> when no file exists. Already handled.</p>
<hr />
<h2>Red → Green → Refactor: Side-Effect Isolation</h2>
<p>A critical property of a well-behaved store: <strong>one instance's operations don't affect another instance pointing to the same URL</strong>.</p>
<pre><code class="language-swift">func test_sideEffects_runSerially() throws {
    let sut = makeSUT()
    let items = makeItems()

    try sut.save(items)
    let loaded = try sut.load()

    XCTAssertEqual(loaded, items)
}
</code></pre>
<p>And a test for concurrent access safety — two instances, same URL:</p>
<pre><code class="language-swift">func test_save_doesNotAffectAnotherInstanceWithSameURL() throws {
    let instance1 = makeSUT()
    let instance2 = makeSUT()
    let items = makeItems()

    try instance1.save(items)
    let loaded = try instance2.load()

    XCTAssertEqual(loaded, items)
}
</code></pre>
<p>Both pass — file system access with <code>.atomic</code> writes is safe for this use case.</p>
<hr />
<h2>The Final Test Suite</h2>
<pre><code class="language-swift">final class CodableFeedStoreTests: XCTestCase {

    override func setUp() {
        super.setUp()
        deleteStoreArtifacts()
    }

    override func tearDown() {
        super.tearDown()
        deleteStoreArtifacts()
    }

    func test_load_deliversEmptyResultOnEmptyCache() throws {
        XCTAssertEqual(try makeSUT().load(), [])
    }

    func test_load_deliversItemsPreviouslySaved() throws {
        let sut = makeSUT()
        let items = makeItems()
        try sut.save(items)
        XCTAssertEqual(try sut.load(), items)
    }

    func test_load_deliversLastSavedItemsOnMultipleSaves() throws {
        let sut = makeSUT()
        let latest = [FeedItem(id: UUID(), title: "Latest", imageURL: anyURL())]
        try sut.save(makeItems())
        try sut.save(latest)
        XCTAssertEqual(try sut.load(), latest)
    }

    func test_load_deliversEmptyResultAfterDeletion() throws {
        let sut = makeSUT()
        try sut.save(makeItems())
        try sut.delete()
        XCTAssertEqual(try sut.load(), [])
    }

    // MARK: - Helpers

    private func makeSUT(file: StaticString = #file, line: UInt = #line) -&gt; FeedStore {
        let sut = CodableFeedStore(storeURL: testSpecificStoreURL())
        trackForMemoryLeaks(sut, file: file, line: line)
        return sut
    }

    private func testSpecificStoreURL() -&gt; URL {
        FileManager.default
            .urls(for: .cachesDirectory, in: .userDomainMask)[0]
            .appendingPathComponent("\(type(of: self)).store")
    }

    private func deleteStoreArtifacts() {
        try? FileManager.default.removeItem(at: testSpecificStoreURL())
    }

    private func makeItems() -&gt; [FeedItem] {
        [
            FeedItem(id: UUID(), title: "First", imageURL: anyURL()),
            FeedItem(id: UUID(), title: "Second", imageURL: anyURL())
        ]
    }

    private func anyURL() -&gt; URL { URL(string: "https://any-url.com")! }
}
</code></pre>
<hr />
<h2>Plugging It Into the System</h2>
<p><code>CodableFeedStore</code> implements <code>FeedStore</code>. The <code>CachingFeedRepository</code> from the previous article expects a <code>FeedCacheStore</code>. To connect them, either unify the protocol or add a simple adapter at the Composition Root.</p>
<p>The Composition Root stays the single place where concrete types meet:</p>
<pre><code class="language-swift">let store = CodableFeedStore(
    storeURL: FileManager.default
        .urls(for: .cachesDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("feed.store")
)

let repository = CachingFeedRepository(
    decoratee: RemoteFeedRepository(url: feedURL),
    cache: store
)
</code></pre>
<hr />
<h2>What TDD Gave Us Here</h2>
<table>
<thead>
<tr>
<th>Without TDD</th>
<th>With TDD</th>
</tr>
</thead>
<tbody><tr>
<td>Tests shaped by existing implementation</td>
<td>Implementation shaped by required behaviour</td>
</tr>
<tr>
<td>Easy to miss edge cases</td>
<td>Each edge case is a deliberate test</td>
</tr>
<tr>
<td>Memory leaks discovered in production</td>
<td>Caught at test time via teardown tracking</td>
</tr>
<tr>
<td>Test pollution between runs</td>
<td><code>setUp</code>/<code>tearDown</code> enforced isolation</td>
</tr>
<tr>
<td>Large class before any feedback</td>
<td>Smallest possible class at each step</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>TDD is not about writing tests — it's about <strong>designing through tests</strong>. Each Red phase asks: <em>what behaviour do I need?</em> Each Green phase asks: <em>what's the minimum code to deliver it?</em> Each Refactor phase asks: <em>how do I keep the code clean without changing its behaviour?</em></p>
<p>For a cache layer, TDD delivers:</p>
<ol>
<li><p>A clear, minimal interface driven by actual use.</p>
</li>
<li><p>Guaranteed isolation between test runs.</p>
</li>
<li><p>Memory leak detection built into the test harness.</p>
</li>
<li><p>Confidence that every behaviour is covered — because no behaviour was written without a test that demanded it.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Single Responsibility: Breaking Up Fat ViewModels in SwiftUI]]></title><description><![CDATA[The Single Responsibility Principle (SRP) states that a class should have one reason to change. It's the first letter of SOLID, and arguably the one most…]]></description><link>https://swiftuicentral.com/single-responsibility-breaking-up-fat-viewmodels-in-swiftui</link><guid isPermaLink="true">https://swiftuicentral.com/single-responsibility-breaking-up-fat-viewmodels-in-swiftui</guid><category><![CDATA[iOS]]></category><category><![CDATA[ViewModel]]></category><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Fri, 08 May 2026 08:44:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/dec2f515-cf4e-4bda-a8f4-b1ba43bac891.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Single Responsibility Principle (SRP) states that a class should have <strong>one reason to change</strong>. It's the first letter of SOLID, and arguably the one most frequently violated in SwiftUI projects.</p>
<p>The culprit is almost always the ViewModel.</p>
<p>It starts innocently: a ViewModel fetches data, formats it for display, handles user input, manages navigation state, and tracks analytics. Each of these is a separate <em>reason to change</em> — an API contract update, a design change, a product decision about analytics — but they all live in the same class. The ViewModel becomes a liability: hard to read, harder to test, and impossible to reuse.</p>
<p>This article shows how to identify SRP violations in a SwiftUI ViewModel, and how to decompose them into focused, testable units.</p>
<hr />
<h2>The Fat ViewModel</h2>
<p>Here's a realistic example — a profile screen ViewModel that has grown organically:</p>
<pre><code class="language-swift">final class ProfileViewModel: ObservableObject {
    @Published var displayName: String = ""
    @Published var avatarURL: URL?
    @Published var followerCount: String = ""
    @Published var isLoading = false
    @Published var errorMessage: String?
    @Published var navigateToEdit = false

    private let userID: UUID
    private let apiClient: APIClient
    private let analytics: AnalyticsTracker
    private let dateFormatter: DateFormatter

    init(userID: UUID, apiClient: APIClient, analytics: AnalyticsTracker) {
        self.userID = userID
        self.apiClient = apiClient
        self.analytics = analytics
        self.dateFormatter = DateFormatter()
        self.dateFormatter.dateStyle = .medium
    }

    func onAppear() async {
        analytics.track("profile_viewed", properties: ["user_id": userID.uuidString])

        isLoading = true
        do {
            let user = try await apiClient.fetchUser(id: userID)
            displayName = "\(user.firstName) \(user.lastName)"
            avatarURL = user.avatarURL
            followerCount = formatFollowerCount(user.followerCount)
        } catch {
            errorMessage = "Failed to load profile."
        }
        isLoading = false
    }

    func onEditTapped() {
        analytics.track("edit_profile_tapped")
        navigateToEdit = true
    }

    private func formatFollowerCount(_ count: Int) -&gt; String {
        count &gt;= 1000
            ? String(format: "%.1fK", Double(count) / 1000)
            : "\(count)"
    }
}
</code></pre>
<p>This ViewModel has at least <strong>four distinct reasons to change</strong>:</p>
<ol>
<li><p><strong>Data fetching</strong>: the API shape changes.</p>
</li>
<li><p><strong>Display formatting</strong>: design decides follower counts should show "1.2M" instead of "1.2K".</p>
</li>
<li><p><strong>Navigation</strong>: the app moves to a coordinator or router pattern.</p>
</li>
<li><p><strong>Analytics</strong>: the tracking library is replaced.</p>
</li>
</ol>
<p>Each of these is an independent concern. Bundled together, a change to any one of them requires understanding — and risking — all the others.</p>
<hr />
<h2>Step 1 — Extract Formatting into a Presenter</h2>
<p>Formatting logic is pure and stateless. It takes a domain value and returns a display string. It deserves its own type.</p>
<pre><code class="language-swift">// Presentation/ProfilePresenter.swift
struct ProfilePresenter {
    func displayName(firstName: String, lastName: String) -&gt; String {
        "\(firstName) \(lastName)"
    }

    func followerCount(_ count: Int) -&gt; String {
        count &gt;= 1_000_000 ? String(format: "%.1fM", Double(count) / 1_000_000)
        : count &gt;= 1_000   ? String(format: "%.1fK", Double(count) / 1_000)
        : "\(count)"
    }
}
</code></pre>
<p>This is now <strong>trivially testable</strong> without instantiating a ViewModel or mocking any dependency:</p>
<pre><code class="language-swift">final class ProfilePresenterTests: XCTestCase {

    private let sut = ProfilePresenter()

    func test_followerCount_belowThousand() {
        XCTAssertEqual(sut.followerCount(842), "842")
    }

    func test_followerCount_thousands() {
        XCTAssertEqual(sut.followerCount(1_200), "1.2K")
    }

    func test_followerCount_millions() {
        XCTAssertEqual(sut.followerCount(2_500_000), "2.5M")
    }

    func test_displayName_combinesFirstAndLast() {
        XCTAssertEqual(sut.displayName(firstName: "Ada", lastName: "Lovelace"), "Ada Lovelace")
    }
}
</code></pre>
<hr />
<h2>Step 2 — Extract Analytics into a Use Case Decorator</h2>
<p>Analytics is a cross-cutting concern. It doesn't belong in the ViewModel — it belongs in a Decorator around the use case that triggers the tracking.</p>
<pre><code class="language-swift">// Domain/UseCases/LoadProfileUseCase.swift
protocol LoadProfileUseCase {
    func execute(userID: UUID) async throws -&gt; UserProfile
}

final class RemoteLoadProfileUseCase: LoadProfileUseCase {
    private let apiClient: APIClient

    init(apiClient: APIClient) { self.apiClient = apiClient }

    func execute(userID: UUID) async throws -&gt; UserProfile {
        try await apiClient.fetchUser(id: userID)
    }
}
</code></pre>
<pre><code class="language-swift">// Presentation/AnalyticsDecorator.swift
final class AnalyticsLoadProfileUseCase: LoadProfileUseCase {
    private let decoratee: LoadProfileUseCase
    private let analytics: AnalyticsTracker

    init(decoratee: LoadProfileUseCase, analytics: AnalyticsTracker) {
        self.decoratee = decoratee
        self.analytics = analytics
    }

    func execute(userID: UUID) async throws -&gt; UserProfile {
        analytics.track("profile_viewed", properties: ["user_id": userID.uuidString])
        return try await decoratee.execute(userID: userID)
    }
}
</code></pre>
<p>Analytics tracking is now independently testable and doesn't pollute the ViewModel.</p>
<hr />
<h2>Step 3 — Extract Navigation into a Coordinator</h2>
<p>Navigation state doesn't belong in the ViewModel either — the ViewModel shouldn't know where the app goes next.</p>
<pre><code class="language-swift">// Presentation/ProfileCoordinator.swift
protocol ProfileCoordinator {
    func showEditProfile()
}
</code></pre>
<p>The concrete implementation lives in the Composition Root or a dedicated coordinator object, not in the ViewModel.</p>
<hr />
<h2>Step 4 — The Slim ViewModel</h2>
<p>With formatting, analytics, and navigation extracted, the ViewModel has one job: <strong>coordinate loading state and expose display data</strong>.</p>
<pre><code class="language-swift">@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var displayName: String = ""
    @Published private(set) var avatarURL: URL?
    @Published private(set) var followerCount: String = ""
    @Published private(set) var isLoading = false
    @Published private(set) var errorMessage: String?

    private let userID: UUID
    private let loadProfile: LoadProfileUseCase
    private let presenter: ProfilePresenter
    private let coordinator: ProfileCoordinator

    init(
        userID: UUID,
        loadProfile: LoadProfileUseCase,
        presenter: ProfilePresenter,
        coordinator: ProfileCoordinator
    ) {
        self.userID = userID
        self.loadProfile = loadProfile
        self.presenter = presenter
        self.coordinator = coordinator
    }

    func onAppear() async {
        isLoading = true
        errorMessage = nil
        do {
            let user = try await loadProfile.execute(userID: userID)
            displayName = presenter.displayName(firstName: user.firstName, lastName: user.lastName)
            avatarURL = user.avatarURL
            followerCount = presenter.followerCount(user.followerCount)
        } catch {
            errorMessage = "Failed to load profile."
        }
        isLoading = false
    }

    func onEditTapped() {
        coordinator.showEditProfile()
    }
}
</code></pre>
<p>Every dependency is explicit. The ViewModel has one reason to change: <strong>how it coordinates loading state and maps domain data to display data</strong>.</p>
<hr />
<h2>Testing the Slim ViewModel</h2>
<pre><code class="language-swift">final class ProfileViewModelTests: XCTestCase {

    func test_onAppear_exposesFormattedDataOnSuccess() async {
        let profile = UserProfile(firstName: "Ada", lastName: "Lovelace",
                                  avatarURL: anyURL(), followerCount: 1200)
        let (sut, _, _) = makeSUT(loadResult: .success(profile))

        await sut.onAppear()

        XCTAssertEqual(sut.displayName, "Ada Lovelace")
        XCTAssertEqual(sut.followerCount, "1.2K")
        XCTAssertNil(sut.errorMessage)
        XCTAssertFalse(sut.isLoading)
    }

    func test_onAppear_exposesErrorMessageOnFailure() async {
        let (sut, _, _) = makeSUT(loadResult: .failure(anyError()))

        await sut.onAppear()

        XCTAssertNotNil(sut.errorMessage)
        XCTAssertTrue(sut.displayName.isEmpty)
    }

    func test_onEditTapped_triggersCoordinator() {
        let (sut, _, coordinator) = makeSUT(loadResult: .success(anyProfile()))

        sut.onEditTapped()

        XCTAssertTrue(coordinator.showEditProfileCalled)
    }

    // MARK: - Helpers

    private func makeSUT(
        loadResult: Result&lt;UserProfile, Error&gt;
    ) -&gt; (ProfileViewModel, LoadProfileUseCaseStub, ProfileCoordinatorSpy) {
        let useCase = LoadProfileUseCaseStub(result: loadResult)
        let coordinator = ProfileCoordinatorSpy()
        let sut = ProfileViewModel(
            userID: UUID(),
            loadProfile: useCase,
            presenter: ProfilePresenter(),
            coordinator: coordinator
        )
        return (sut, useCase, coordinator)
    }

    private func anyURL() -&gt; URL { URL(string: "https://any-url.com")! }
    private func anyError() -&gt; Error { NSError(domain: "test", code: 0) }
    private func anyProfile() -&gt; UserProfile {
        UserProfile(firstName: "A", lastName: "B", avatarURL: anyURL(), followerCount: 0)
    }
}

private class LoadProfileUseCaseStub: LoadProfileUseCase {
    private let result: Result&lt;UserProfile, Error&gt;
    init(result: Result&lt;UserProfile, Error&gt;) { self.result = result }
    func execute(userID: UUID) async throws -&gt; UserProfile { try result.get() }
}

private class ProfileCoordinatorSpy: ProfileCoordinator {
    var showEditProfileCalled = false
    func showEditProfile() { showEditProfileCalled = true }
}
</code></pre>
<p>Each test verifies one behaviour. The ViewModel, presenter, and analytics decorator each have their own test suite.</p>
<hr />
<h2>Recognising SRP Violations</h2>
<p>Ask these questions about any ViewModel:</p>
<table>
<thead>
<tr>
<th>Question</th>
<th>If yes → extract to...</th>
</tr>
</thead>
<tbody><tr>
<td>Does it format strings or dates?</td>
<td><code>Presenter</code> / <code>Formatter</code></td>
</tr>
<tr>
<td>Does it track analytics events?</td>
<td><code>AnalyticsDecorator</code> around the use case</td>
</tr>
<tr>
<td>Does it set navigation flags?</td>
<td><code>Coordinator</code></td>
</tr>
<tr>
<td>Does it call multiple APIs?</td>
<td>Separate <code>UseCase</code> per operation</td>
</tr>
<tr>
<td>Does it manage local state (e.g. a timer)?</td>
<td>Dedicated <code>StateController</code></td>
</tr>
</tbody></table>
<p>Each extraction makes the original class smaller, the new class independently testable, and the system as a whole easier to change.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Fat ViewModel</th>
<th>Decomposed</th>
</tr>
</thead>
<tbody><tr>
<td>Multiple reasons to change</td>
<td>One reason to change per class</td>
</tr>
<tr>
<td>Hard to test in isolation</td>
<td>Every unit tested independently</td>
</tr>
<tr>
<td>Formatting bugs require ViewModel knowledge</td>
<td>Presenter tests catch them instantly</td>
</tr>
<tr>
<td>Analytics change requires touching business logic</td>
<td>Decorator swapped at Composition Root</td>
</tr>
<tr>
<td>Navigation logic couples view to routing</td>
<td>Coordinator owns routing decisions</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>The Single Responsibility Principle is not about keeping classes small for the sake of it — it's about ensuring <strong>each class changes for exactly one reason</strong>. In SwiftUI ViewModels:</p>
<ol>
<li><p>Extract <strong>formatting</strong> into a <code>Presenter</code> — pure, stateless, trivially testable.</p>
</li>
<li><p>Extract <strong>analytics</strong> into a <code>Decorator</code> around the use case — added at the Composition Root, invisible to the ViewModel.</p>
</li>
<li><p>Extract <strong>navigation</strong> into a <code>Coordinator</code> — the ViewModel tells the coordinator <em>what happened</em>, the coordinator decides <em>where to go</em>.</p>
</li>
<li><p>The ViewModel's only job: coordinate loading state and map domain data to display data.</p>
</li>
</ol>
<p>A class that does one thing is a class you can trust.</p>
]]></content:encoded></item><item><title><![CDATA[Applying the Decorator Pattern in SwiftUI to Add Caching Without Changing Existing Code]]></title><description><![CDATA[You've built a clean feed feature. The RemoteFeedRepository fetches items from the network, the LoadFeedUseCase runs the business logic, and the ViewModel…]]></description><link>https://swiftuicentral.com/applying-the-decorator-pattern-in-swiftui-to-add-caching-without-changing-existing-code</link><guid isPermaLink="true">https://swiftuicentral.com/applying-the-decorator-pattern-in-swiftui-to-add-caching-without-changing-existing-code</guid><category><![CDATA[iOS]]></category><category><![CDATA[decorators]]></category><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Sat, 02 May 2026 11:55:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/b4d98b24-a34a-4de1-8902-876c67566def.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've built a clean feed feature. The <code>RemoteFeedRepository</code> fetches items from the network, the <code>LoadFeedUseCase</code> runs the business logic, and the ViewModel drives the view. Everything is tested and working.</p>
<p>Now a new requirement arrives: <strong>cache the last successful response</strong> so the app shows content immediately on relaunch, even without a network connection.</p>
<p>The naive approach is to open <code>RemoteFeedRepository</code> and add caching logic directly. But that violates the <strong>Open/Closed Principle</strong> — code should be open for extension, closed for modification. Modifying a working, tested class to add new behavior risks breaking existing functionality and bloats a class that previously had one job.</p>
<p>The <strong>Decorator pattern</strong> gives you a better path: wrap the existing repository with a new object that adds caching on top, without touching a single line of the original.</p>
<hr />
<h2>Recap: The Existing Structure</h2>
<p>From the previous article, the Domain layer defines:</p>
<pre><code class="language-swift">protocol FeedRepository {
    func fetchFeed() async throws -&gt; [FeedItem]
}
</code></pre>
<p>And the Data layer provides:</p>
<pre><code class="language-swift">final class RemoteFeedRepository: FeedRepository {
    func fetchFeed() async throws -&gt; [FeedItem] {
        // fetches from network
    }
}
</code></pre>
<p>The <code>LoadFeedUseCase</code> depends only on the <code>FeedRepository</code> protocol — it has no idea what sits behind it.</p>
<hr />
<h2>Step 1 — Build the Decorator</h2>
<p>A Decorator implements the same protocol as the type it wraps, and holds a reference to the wrapped instance. It intercepts calls, adds behavior, and delegates the core work.</p>
<p>First, define a simple cache store:</p>
<pre><code class="language-swift">// Data/Cache/FeedCacheStore.swift
protocol FeedCacheStore {
    func save(_ items: [FeedItem]) throws
    func load() throws -&gt; [FeedItem]
}
</code></pre>
<p>Now create the Decorator:</p>
<pre><code class="language-swift">// Data/Cache/CachingFeedRepository.swift
final class CachingFeedRepository: FeedRepository {
    private let decoratee: FeedRepository
    private let cache: FeedCacheStore

    init(decoratee: FeedRepository, cache: FeedCacheStore) {
        self.decoratee = decoratee
        self.cache = cache
    }

    func fetchFeed() async throws -&gt; [FeedItem] {
        do {
            let items = try await decoratee.fetchFeed()
            try? cache.save(items)
            return items
        } catch {
            if let cachedItems = try? cache.load(), !cachedItems.isEmpty {
                return cachedItems
            }
            throw error
        }
    }
}
</code></pre>
<p>The logic is explicit:</p>
<ol>
<li><p>Try the real repository (network).</p>
</li>
<li><p>On success, save to cache and return the fresh items.</p>
</li>
<li><p>On failure, fall back to the cache if available.</p>
</li>
<li><p>If both fail, propagate the original error.</p>
</li>
</ol>
<p><code>RemoteFeedRepository</code> is untouched. The caching logic lives in its own class with its own tests.</p>
<hr />
<h2>Step 2 — Implement the Cache Store</h2>
<p>For a concrete implementation, <code>UserDefaults</code> works well for lightweight data. For larger datasets, use Core Data or the file system.</p>
<pre><code class="language-swift">// Data/Cache/UserDefaultsFeedCacheStore.swift
final class UserDefaultsFeedCacheStore: FeedCacheStore {
    private let defaults: UserDefaults
    private let key = "cached_feed"

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func save(_ items: [FeedItem]) throws {
        let data = try JSONEncoder().encode(items)
        defaults.set(data, forKey: key)
    }

    func load() throws -&gt; [FeedItem] {
        guard let data = defaults.data(forKey: key) else {
            return []
        }
        return try JSONDecoder().decode([FeedItem].self, from: data)
    }
}
</code></pre>
<p>Note: <code>FeedItem</code> needs <code>Codable</code> conformance for this to work. Add it in the Domain layer:</p>
<pre><code class="language-swift">struct FeedItem: Equatable, Codable {
    let id: UUID
    let title: String
    let imageURL: URL
}
</code></pre>
<hr />
<h2>Step 3 — Wire It in the Composition Root</h2>
<p>Only one change is needed in the entire codebase — at the Composition Root:</p>
<pre><code class="language-swift">// Before
FeedView(
    viewModel: FeedViewModel(
        loadFeed: LoadFeedUseCase(
            repository: RemoteFeedRepository(url: feedURL)
        )
    )
)

// After
FeedView(
    viewModel: FeedViewModel(
        loadFeed: LoadFeedUseCase(
            repository: CachingFeedRepository(
                decoratee: RemoteFeedRepository(url: feedURL),
                cache: UserDefaultsFeedCacheStore()
            )
        )
    )
)
</code></pre>
<p>The <code>LoadFeedUseCase</code> and <code>FeedViewModel</code> have no idea a cache was added. The <code>RemoteFeedRepository</code> has no idea it's wrapped. Every existing test still passes without modification.</p>
<hr />
<h2>Step 4 — Test the Decorator in Isolation</h2>
<p>The Decorator is fully testable without a real network or real storage:</p>
<pre><code class="language-swift">final class CachingFeedRepositoryTests: XCTestCase {

    func test_fetchFeed_savesRemoteItemsToCache() async throws {
        let remoteItems = makeItems()
        let (sut, remote, cache) = makeSUT(remoteResult: .success(remoteItems))

        _ = try await sut.fetchFeed()

        XCTAssertEqual(cache.savedItems, remoteItems)
    }

    func test_fetchFeed_returnsRemoteItemsOnSuccess() async throws {
        let remoteItems = makeItems()
        let (sut, _, _) = makeSUT(remoteResult: .success(remoteItems))

        let received = try await sut.fetchFeed()

        XCTAssertEqual(received, remoteItems)
    }

    func test_fetchFeed_returnsCachedItemsOnRemoteFailure() async throws {
        let cachedItems = makeItems()
        let (sut, _, cache) = makeSUT(remoteResult: .failure(anyError()))
        cache.stubbedItems = cachedItems

        let received = try await sut.fetchFeed()

        XCTAssertEqual(received, cachedItems)
    }

    func test_fetchFeed_throwsWhenRemoteFailsAndCacheIsEmpty() async {
        let (sut, _, _) = makeSUT(remoteResult: .failure(anyError()))

        do {
            _ = try await sut.fetchFeed()
            XCTFail("Expected error to be thrown")
        } catch {
            XCTAssertNotNil(error)
        }
    }

    // MARK: - Helpers

    private func makeSUT(
        remoteResult: Result&lt;[FeedItem], Error&gt;
    ) -&gt; (CachingFeedRepository, FeedRepositoryStub, FeedCacheStoreSpy) {
        let remote = FeedRepositoryStub(result: remoteResult)
        let cache = FeedCacheStoreSpy()
        let sut = CachingFeedRepository(decoratee: remote, cache: cache)
        return (sut, remote, cache)
    }

    private func makeItems() -&gt; [FeedItem] {
        [FeedItem(id: UUID(), title: "Item", imageURL: URL(string: "https://any-url.com")!)]
    }

    private func anyError() -&gt; Error { NSError(domain: "test", code: 0) }
}

// MARK: - Test Doubles

private class FeedRepositoryStub: FeedRepository {
    private let result: Result&lt;[FeedItem], Error&gt;
    init(result: Result&lt;[FeedItem], Error&gt;) { self.result = result }
    func fetchFeed() async throws -&gt; [FeedItem] { try result.get() }
}

private class FeedCacheStoreSpy: FeedCacheStore {
    var savedItems: [FeedItem] = []
    var stubbedItems: [FeedItem] = []

    func save(_ items: [FeedItem]) throws { savedItems = items }
    func load() throws -&gt; [FeedItem] { stubbedItems }
}
</code></pre>
<p>Four focused tests. Each verifies one behaviour. No real network, no real disk.</p>
<hr />
<h2>Stacking Decorators</h2>
<p>Because every Decorator implements the same protocol, they compose freely. Need to add <strong>logging</strong> on top of caching?</p>
<pre><code class="language-swift">final class LoggingFeedRepository: FeedRepository {
    private let decoratee: FeedRepository
    private let logger: Logger

    init(decoratee: FeedRepository, logger: Logger = Logger()) {
        self.decoratee = decoratee
        self.logger = logger
    }

    func fetchFeed() async throws -&gt; [FeedItem] {
        logger.log("Fetching feed...")
        do {
            let items = try await decoratee.fetchFeed()
            logger.log("Fetched \(items.count) items.")
            return items
        } catch {
            logger.log("Fetch failed: \(error)")
            throw error
        }
    }
}
</code></pre>
<p>Wire them in the Composition Root by nesting:</p>
<pre><code class="language-swift">repository: LoggingFeedRepository(
    decoratee: CachingFeedRepository(
        decoratee: RemoteFeedRepository(url: feedURL),
        cache: UserDefaultsFeedCacheStore()
    )
)
</code></pre>
<p>Each Decorator has one job. Each is independently testable. The core remote logic stays pristine.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Concern</th>
<th>Without Decorator</th>
<th>With Decorator</th>
</tr>
</thead>
<tbody><tr>
<td>Adding caching</td>
<td>Modify <code>RemoteFeedRepository</code></td>
<td>Create a new, separate class</td>
</tr>
<tr>
<td>Open/Closed Principle</td>
<td>Violated on every new requirement</td>
<td>Each new behavior is a new class</td>
</tr>
<tr>
<td>Testability</td>
<td>One large class tests multiple concerns</td>
<td>Each Decorator tested in isolation</td>
</tr>
<tr>
<td>Composability</td>
<td>Hard-coded behaviour chains</td>
<td>Freely nestable at the Composition Root</td>
</tr>
<tr>
<td>Risk</td>
<td>Changing working code risks regression</td>
<td>Existing code and tests untouched</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>The Decorator pattern is one of the most powerful tools in a clean architecture toolkit. In SwiftUI:</p>
<ol>
<li><p>Define behavior through a <strong>protocol</strong> (<code>FeedRepository</code>).</p>
</li>
<li><p>Implement the core behavior in a focused class (<code>RemoteFeedRepository</code>).</p>
</li>
<li><p>Add new cross-cutting concerns — caching, logging, analytics, retry logic — by <strong>wrapping</strong> the existing implementation in a Decorator.</p>
</li>
<li><p><strong>Compose</strong> at the Composition Root by nesting Decorators.</p>
</li>
<li><p>Test each Decorator independently using stubs.</p>
</li>
</ol>
<p>Every new requirement becomes a new class, not a modification to an existing one. The codebase grows by addition, not by mutation — and every piece remains testable, readable, and replaceable.</p>
]]></content:encoded></item><item><title><![CDATA[Clean Architecture in SwiftUI: Separating Domain, Data, and Presentation]]></title><description><![CDATA[Most SwiftUI apps start simple. A ViewModel fetches data from an API, maps it to a model, and drives a view. It works. But as the app grows, the ViewModel…]]></description><link>https://swiftuicentral.com/clean-architecture-in-swiftui-separating-domain-data-and-presentation</link><guid isPermaLink="true">https://swiftuicentral.com/clean-architecture-in-swiftui-separating-domain-data-and-presentation</guid><category><![CDATA[iOS]]></category><category><![CDATA[Clean Architecture]]></category><category><![CDATA[SwiftUI]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Wed, 22 Apr 2026 20:56:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/1dfedcf9-2c43-450c-8e38-7a876ffbe715.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most SwiftUI apps start simple. A ViewModel fetches data from an API, maps it to a model, and drives a view. It works. But as the app grows, the ViewModel becomes a god object: it knows about URLs, JSON decoding, business rules, navigation, and UI state all at once.</p>
<p>When everything lives in one place, changing one thing breaks another. Testing requires mocking the entire world. And understanding any single piece of logic means reading through unrelated concerns.</p>
<p>Clean Architecture solves this by enforcing <strong>a strict separation between three layers</strong>: Domain, Data, and Presentation. Each layer has one job, depends only inward, and can be tested in complete isolation.</p>
<p>This article walks through a concrete feature — loading a list of feed items — and builds it layer by layer.</p>
<hr />
<h2>The Layered Model</h2>
<p><strong>Presentation -&gt;</strong> SwiftUI Views + ViewModels<br /><strong>Domain -&gt;</strong> Use Cases + Entities + Interfaces<br /><strong>Data -&gt;</strong> Network / Persistance / Mappers</p>
<p><strong>The Dependency Rule</strong>: outer layers depend on inner layers. The <strong>Domain</strong> layer depends on nothing. The <strong>Data</strong> layer implements <strong>Domain</strong> interfaces. The <strong>Presentation</strong> layer calls <strong>Domain</strong> use cases.</p>
<hr />
<h2>Step 1 — The Domain Layer</h2>
<p>The Domain layer is the heart of your app. It contains:</p>
<ul>
<li><p><strong>Entities</strong>: pure data models with no framework imports.</p>
</li>
<li><p><strong>Use Case interfaces</strong>: what the app <em>can do</em>, expressed as protocols.</p>
</li>
<li><p><strong>Repository interfaces</strong>: what data the app <em>needs</em>, expressed as protocols.</p>
</li>
</ul>
<pre><code class="language-swift">// Domain/Models/FeedItem.swift
struct FeedItem: Equatable {
    let id: UUID
    let title: String
    let imageURL: URL
}
</code></pre>
<pre><code class="language-swift">// Domain/Interfaces/FeedRepository.swift
protocol FeedRepository {
    func fetchFeed() async throws -&gt; [FeedItem]
}
</code></pre>
<pre><code class="language-swift">// Domain/UseCases/LoadFeedUseCase.swift
final class LoadFeedUseCase {
    private let repository: FeedRepository

    init(repository: FeedRepository) {
        self.repository = repository
    }

    func execute() async throws -&gt; [FeedItem] {
        try await repository.fetchFeed()
    }
}
</code></pre>
<p>Notice: <strong>zero imports of Foundation, UIKit, or SwiftUI</strong> in these files. The Domain layer is a pure Swift module. It can run anywhere — on a server, in a CLI tool, in a test harness — without modification.</p>
<h3>Testing the Domain Layer</h3>
<p>The use case is trivially testable:</p>
<pre><code class="language-swift">final class LoadFeedUseCaseTests: XCTestCase {

    func test_execute_deliversItemsFromRepository() async throws {
        let expectedItems = [
            FeedItem(id: UUID(), title: "Article A", imageURL: anyURL()),
            FeedItem(id: UUID(), title: "Article B", imageURL: anyURL())
        ]
        let repository = FeedRepositoryStub(result: .success(expectedItems))
        let sut = LoadFeedUseCase(repository: repository)

        let items = try await sut.execute()

        XCTAssertEqual(items, expectedItems)
    }

    func test_execute_throwsOnRepositoryFailure() async {
        let repository = FeedRepositoryStub(result: .failure(anyError()))
        let sut = LoadFeedUseCase(repository: repository)

        do {
            _ = try await sut.execute()
            XCTFail("Expected error to be thrown")
        } catch {
            XCTAssertNotNil(error)
        }
    }

    // MARK: - Helpers

    private func anyURL() -&gt; URL { URL(string: "https://any-url.com")! }
    private func anyError() -&gt; Error { NSError(domain: "test", code: 0) }
}

private class FeedRepositoryStub: FeedRepository {
    private let result: Result&lt;[FeedItem], Error&gt;

    init(result: Result&lt;[FeedItem], Error&gt;) {
        self.result = result
    }

    func fetchFeed() async throws -&gt; [FeedItem] {
        try result.get()
    }
}
</code></pre>
<p>No network. No UI. No SwiftUI. The Domain layer tests run in milliseconds.</p>
<hr />
<h2>Step 2 — The Data Layer</h2>
<p>The Data layer implements the Domain interfaces using real infrastructure: URLSession, CoreData, Keychain, etc. It also maps external representations (JSON) to Domain entities.</p>
<pre><code class="language-swift">// Data/Remote/RemoteFeedItem.swift
private struct RemoteFeedItem: Decodable {
    let id: UUID
    let title: String
    let image_url: URL
}
</code></pre>
<pre><code class="language-swift">// Data/Remote/RemoteFeedRepository.swift
final class RemoteFeedRepository: FeedRepository {
    private let url: URL
    private let session: URLSession

    init(url: URL, session: URLSession = .shared) {
        self.url = url
        self.session = session
    }

    func fetchFeed() async throws -&gt; [FeedItem] {
        let (data, response) = try await session.data(from: url)

        guard let httpResponse = response as? HTTPURLResponse,
              httpResponse.statusCode == 200 else {
            throw RemoteFeedError.invalidResponse
        }

        let remoteItems = try JSONDecoder().decode([RemoteFeedItem].self, from: data)
        return remoteItems.map { FeedItem(id: \(0.id, title: \)0.title, imageURL: $0.image_url) }
    }

    enum RemoteFeedError: Error {
        case invalidResponse
    }
}
</code></pre>
<p>The mapping from <code>RemoteFeedItem</code> → <code>FeedItem</code> happens <strong>inside the Data layer</strong>. The Domain layer never sees the JSON structure. If the API changes its field names, only the mapper changes — the Domain and Presentation layers are untouched.</p>
<h3>Testing the Data Layer</h3>
<p>Test with a controlled <code>URLSession</code> using <code>URLProtocol</code> stubs, or inject a mock session:</p>
<pre><code class="language-swift">final class RemoteFeedRepositoryTests: XCTestCase {

    func test_fetchFeed_deliversMappedItemsOn200Response() async throws {
        let expectedItems = makeItems()
        let (sut, session) = makeSUT()
        session.stub(url: feedURL, data: makeJSON(expectedItems), statusCode: 200)

        let items = try await sut.fetchFeed()

        XCTAssertEqual(items, expectedItems.map(\.domain))
    }

    func test_fetchFeed_throwsOnNon200Response() async {
        let (sut, session) = makeSUT()
        session.stub(url: feedURL, data: Data(), statusCode: 400)

        do {
            _ = try await sut.fetchFeed()
            XCTFail("Expected error")
        } catch {
            XCTAssertNotNil(error)
        }
    }

    // MARK: - Helpers

    private let feedURL = URL(string: "https://api.example.com/feed")!

    private func makeSUT() -&gt; (RemoteFeedRepository, URLSessionSpy) {
        let session = URLSessionSpy()
        let sut = RemoteFeedRepository(url: feedURL, session: session)
        return (sut, session)
    }
}
</code></pre>
<p>The Data layer tests verify <strong>mapping and HTTP handling</strong> — not business rules.</p>
<hr />
<h2>Step 3 — The Presentation Layer</h2>
<p>The Presentation layer contains ViewModels and SwiftUI views. It depends on the Domain layer through use cases — never directly on the Data layer.</p>
<pre><code class="language-swift">// Presentation/FeedViewModel.swift
@MainActor
final class FeedViewModel: ObservableObject {
    @Published private(set) var items: [FeedItem] = []
    @Published private(set) var isLoading = false
    @Published private(set) var errorMessage: String?

    private let loadFeed: LoadFeedUseCase

    init(loadFeed: LoadFeedUseCase) {
        self.loadFeed = loadFeed
    }

    func onAppear() async {
        isLoading = true
        errorMessage = nil

        do {
            items = try await loadFeed.execute()
        } catch {
            errorMessage = "Could not load feed. Please try again."
        }

        isLoading = false
    }
}
</code></pre>
<pre><code class="language-swift">// Presentation/FeedView.swift
struct FeedView: View {
    @StateObject private var viewModel: FeedViewModel

    init(viewModel: FeedViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    var body: some View {
        Group {
            if viewModel.isLoading {
                ProgressView()
            } else if let error = viewModel.errorMessage {
                Text(error).foregroundStyle(.secondary)
            } else {
                List(viewModel.items, id: \.id) { item in
                    Text(item.title)
                }
            }
        }
        .task { await viewModel.onAppear() }
    }
}
</code></pre>
<h3>Testing the Presentation Layer</h3>
<p>The ViewModel is tested against a <code>LoadFeedUseCase</code> backed by a stub repository — no real network, no SwiftUI rendering:</p>
<pre><code class="language-swift">final class FeedViewModelTests: XCTestCase {

    func test_onAppear_showsLoadingThenItems() async {
        let items = [FeedItem(id: UUID(), title: "Hello", imageURL: anyURL())]
        let useCase = LoadFeedUseCase(repository: FeedRepositoryStub(result: .success(items)))
        let sut = await FeedViewModel(loadFeed: useCase)

        await sut.onAppear()

        let receivedItems = await sut.items
        XCTAssertEqual(receivedItems, items)

        let isLoading = await sut.isLoading
        XCTAssertFalse(isLoading)
    }

    func test_onAppear_showsErrorMessageOnFailure() async {
        let useCase = LoadFeedUseCase(repository: FeedRepositoryStub(result: .failure(anyError())))
        let sut = await FeedViewModel(loadFeed: useCase)

        await sut.onAppear()

        let errorMessage = await sut.errorMessage
        XCTAssertNotNil(errorMessage)
    }

    private func anyURL() -&gt; URL { URL(string: "https://any-url.com")! }
    private func anyError() -&gt; Error { NSError(domain: "test", code: 0) }
}
</code></pre>
<hr />
<h2>Step 4 — The Composition Root</h2>
<p>All three layers meet at exactly one place: the Composition Root in your <code>@main</code> struct. This is the <strong>only place</strong> allowed to know about concrete types from all layers.</p>
<pre><code class="language-swift">@main
struct FeedApp: App {
    var body: some Scene {
        WindowGroup {
            FeedView(
                viewModel: FeedViewModel(
                    loadFeed: LoadFeedUseCase(
                        repository: RemoteFeedRepository(
                            url: URL(string: "https://api.example.com/feed")!
                        )
                    )
                )
            )
        }
    }
}
</code></pre>
<p>Everything is wired here and nowhere else. Changing the data source (remote → local cache → Core Data) means changing <strong>one line</strong> in this file.</p>
<hr />
<h2>The Full Picture</h2>
<pre><code class="language-plaintext">FeedApp (@main)
  └─ FeedView
       └─ FeedViewModel          [Presentation]
            └─ LoadFeedUseCase   [Domain]
                 └─ FeedRepository (protocol)
                      └─ RemoteFeedRepository  [Data]
                           └─ URLSession
</code></pre>
<p>Each arrow points inward. Each layer is independently testable. Each layer has a single, clear responsibility.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Concern</th>
<th>Without Clean Architecture</th>
<th>With Clean Architecture</th>
</tr>
</thead>
<tbody><tr>
<td>Business logic</td>
<td>Buried in ViewModels or views</td>
<td>Isolated in the Domain layer</td>
</tr>
<tr>
<td>Changing the API</td>
<td>Ripples across the app</td>
<td>Only the Data layer changes</td>
</tr>
<tr>
<td>Unit testing</td>
<td>Requires mocking everything</td>
<td>Each layer tested independently</td>
</tr>
<tr>
<td>Onboarding</td>
<td>Hard to know where to look</td>
<td>Clear, predictable structure</td>
</tr>
<tr>
<td>Reusing logic</td>
<td>Copy-paste between targets</td>
<td>Use cases are framework-agnostic</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>Clean Architecture is not about complexity — it's about <strong>clear boundaries</strong>. Three layers, one rule: dependencies point inward.</p>
<ul>
<li><p><strong>Domain</strong>: entities, use cases, and repository interfaces. No framework imports.</p>
</li>
<li><p><strong>Data</strong>: implements the interfaces. Maps external data to domain entities.</p>
</li>
<li><p><strong>Presentation</strong>: drives the UI using use cases. Never touches URLSession or CoreData directly.</p>
</li>
<li><p><strong>Composition Root</strong>: wires everything together. Appears once, at the top.</p>
</li>
</ul>
<p>Once this boundary discipline is in place, every other best practice — TDD, the Decorator pattern, feature flags, caching — slots in naturally without disrupting the existing structure.</p>
]]></content:encoded></item><item><title><![CDATA[Dependency Injection in SwiftUI: Composing Views Without Singletons]]></title><description><![CDATA[One of the most common pitfalls in SwiftUI apps is the overuse of singletons and global state. It feels convenient at first — you just reach for…]]></description><link>https://swiftuicentral.com/dependency-injection-in-swiftui-composing-views-without-singletons</link><guid isPermaLink="true">https://swiftuicentral.com/dependency-injection-in-swiftui-composing-views-without-singletons</guid><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Tue, 21 Apr 2026 11:40:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/61f05a2b87fd2728e7cd404a/dfa135aa-0127-401a-b561-1e3636773d45.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most common pitfalls in SwiftUI apps is the overuse of singletons and global state. It feels convenient at first — you just reach for <code>UserDefaults.standard</code>, a shared <code>NetworkService.shared</code>, or a global <code>@EnvironmentObject</code> — but it quietly makes your code untestable, hard to reason about, and tightly coupled.</p>
<p>This article shows how to apply <strong>Dependency Injection (DI)</strong> in SwiftUI to keep your views composable, your ViewModels testable, and your architecture clean.</p>
<hr />
<h2>The Problem: Hidden Dependencies</h2>
<p>Let's say you're building a simple favorites feature. A common approach looks like this:</p>
<pre><code class="language-swift">class FavoritesViewModel: ObservableObject {
    @Published var favorites: [Item] = []

    func loadFavorites() {
        // Directly coupled to a concrete singleton
        favorites = FavoritesStore.shared.getAll()
    }
}
</code></pre>
<p>And the view:</p>
<pre><code class="language-swift">struct FavoritesView: View {
    @StateObject private var viewModel = FavoritesViewModel()

    var body: some View {
        List(viewModel.favorites) { item in
            Text(item.name)
        }
        .onAppear { viewModel.loadFavorites() }
    }
}
</code></pre>
<p>This works at runtime. But try writing a unit test for <code>FavoritesViewModel</code>:</p>
<ul>
<li><p>You can't control what <code>FavoritesStore.shared</code> returns.</p>
</li>
<li><p>Tests become dependent on shared mutable state.</p>
</li>
<li><p>Running tests in parallel risks interference between test cases.</p>
</li>
</ul>
<p>The dependency on <code>FavoritesStore.shared</code> is <strong>hidden inside the ViewModel</strong>. Hidden dependencies are a form of technical debt that compounds over time.</p>
<hr />
<h2>The Solution: Inject Dependencies Through the Initializer</h2>
<p>The fix is to <strong>invert the dependency</strong>: instead of the ViewModel reaching out for what it needs, we <em>give</em> it what it needs.</p>
<p>Start by defining a protocol that abstracts the store:</p>
<pre><code class="language-swift">protocol FavoritesStoreProtocol {
    func getAll() -&gt; [Item]
}
</code></pre>
<p>Make the real store conform to it:</p>
<pre><code class="language-swift">class FavoritesStore: FavoritesStoreProtocol {
    static let shared = FavoritesStore()

    func getAll() -&gt; [Item] {
        // real implementation
    }
}
</code></pre>
<p>Now inject the dependency into the ViewModel:</p>
<pre><code class="language-swift">class FavoritesViewModel: ObservableObject {
    @Published var favorites: [Item] = []

    private let store: FavoritesStoreProtocol

    init(store: FavoritesStoreProtocol) {
        self.store = store
    }

    func loadFavorites() {
        favorites = store.getAll()
    }
}
</code></pre>
<p>The ViewModel no longer knows (or cares) <em>how</em> favorites are retrieved. It only knows <em>what</em> to call.</p>
<hr />
<h2>Making the View Composable</h2>
<p>With DI in place, the view needs to receive a configured ViewModel:</p>
<pre><code class="language-swift">struct FavoritesView: View {
    @StateObject private var viewModel: FavoritesViewModel

    init(viewModel: FavoritesViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    var body: some View {
        List(viewModel.favorites) { item in
            Text(item.name)
        }
        .onAppear { viewModel.loadFavorites() }
    }
}
</code></pre>
<p>The <strong>Composition Root</strong> — where you wire everything together — lives at the entry point of your app:</p>
<pre><code class="language-swift">@main
struct FavoritesApp: App {
    var body: some Scene {
        WindowGroup {
            FavoritesView(
                viewModel: FavoritesViewModel(store: FavoritesStore.shared)
            )
        }
    }
}
</code></pre>
<p>Notice that <code>FavoritesStore.shared</code> appears only once, at the top. The rest of the codebase never references it directly.</p>
<hr />
<h2>Writing Tests Without Infrastructure</h2>
<p>Now you can test the ViewModel in complete isolation with a stub:</p>
<pre><code class="language-swift">class FavoritesStoreStub: FavoritesStoreProtocol {
    var stubbedFavorites: [Item] = []

    func getAll() -&gt; [Item] {
        stubbedFavorites
    }
}
</code></pre>
<pre><code class="language-swift">final class FavoritesViewModelTests: XCTestCase {

    func test_loadFavorites_populatesListWithStoredItems() {
        let store = FavoritesStoreStub()
        store.stubbedFavorites = [Item(name: "SwiftUI"), Item(name: "TDD")]
        let sut = FavoritesViewModel(store: store)

        sut.loadFavorites()

        XCTAssertEqual(sut.favorites.map(\.name), ["SwiftUI", "TDD"])
    }

    func test_loadFavorites_withEmptyStore_producesEmptyList() {
        let store = FavoritesStoreStub()
        let sut = FavoritesViewModel(store: store)

        sut.loadFavorites()

        XCTAssertTrue(sut.favorites.isEmpty)
    }
}
</code></pre>
<p>These tests are:</p>
<ul>
<li><p><strong>Fast</strong> — no network, no disk, no shared state.</p>
</li>
<li><p><strong>Deterministic</strong> — the stub always returns what you configure.</p>
</li>
<li><p><strong>Isolated</strong> — each test controls its own world.</p>
</li>
</ul>
<hr />
<h2>Passing Dependencies Through the View Hierarchy</h2>
<p>For deeper view hierarchies, you have two clean options.</p>
<h3>Option 1: Explicit Passing (Preferred for Testability)</h3>
<p>Pass dependencies through initializers at every level. It's verbose, but the dependency graph is explicit and auditable.</p>
<pre><code class="language-swift">struct RootView: View {
    let store: FavoritesStoreProtocol

    var body: some View {
        NavigationStack {
            FavoritesView(
                viewModel: FavoritesViewModel(store: store)
            )
        }
    }
}
</code></pre>
<h3>Option 2: <code>@EnvironmentObject</code> with a Protocol Wrapper</h3>
<p>When explicit passing becomes impractical (e.g. very deep hierarchies), <code>@EnvironmentObject</code> is acceptable — but inject at the Composition Root, not a singleton:</p>
<pre><code class="language-swift">// Define a concrete container
class AppDependencies: ObservableObject {
    let store: FavoritesStoreProtocol

    init(store: FavoritesStoreProtocol) {
        self.store = store
    }
}

// Inject once at the root
@main
struct FavoritesApp: App {
    var body: some Scene {
        WindowGroup {
            RootView()
                .environmentObject(AppDependencies(store: FavoritesStore.shared))
        }
    }
}
</code></pre>
<p>The key difference from a singleton: you control what goes into <code>AppDependencies</code>. In tests, you inject a stub version. No global mutable state.</p>
<hr />
<h2>Previews for Free</h2>
<p>A nice side effect of DI: Xcode Previews become trivial to configure.</p>
<pre><code class="language-swift">#Preview {
    let store = FavoritesStoreStub()
    store.stubbedFavorites = [
        Item(name: "Dependency Injection"),
        Item(name: "TDD"),
        Item(name: "Clean Architecture")
    ]
    return FavoritesView(viewModel: FavoritesViewModel(store: store))
}
</code></pre>
<p>No more fighting Previews because they hit the real network or real database.</p>
<hr />
<h2>What You Gain</h2>
<table>
<thead>
<tr>
<th>Before (Singleton)</th>
<th>After (DI)</th>
</tr>
</thead>
<tbody><tr>
<td>Hidden dependencies</td>
<td>Explicit, visible dependencies</td>
</tr>
<tr>
<td>Hard to test</td>
<td>Fully unit-testable</td>
</tr>
<tr>
<td>Shared mutable state in tests</td>
<td>Each test controls its own world</td>
</tr>
<tr>
<td>Previews require real infrastructure</td>
<td>Previews use stubs</td>
</tr>
<tr>
<td>Tight coupling</td>
<td>Views and ViewModels are composable</td>
</tr>
</tbody></table>
<hr />
<h2>Summary</h2>
<p>Dependency Injection is not a complex pattern — it's simply the discipline of <strong>giving a component what it needs rather than letting it reach out for it</strong>. In SwiftUI:</p>
<ol>
<li><p>Define protocols for your dependencies.</p>
</li>
<li><p>Inject concrete implementations through initializers.</p>
</li>
<li><p>Wire everything at the Composition Root (your <code>@main</code> struct).</p>
</li>
<li><p>Use stubs in tests and previews.</p>
</li>
</ol>
<p>This one practice unlocks testability, composability, and clear architecture — all at once. It's the foundation on which Clean Architecture, the Decorator pattern, and every other technique rely on.</p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - Decoupling Models]]></title><description><![CDATA[How can we avoid breaking an entire app when a model changes? Decouple each model based on their specific domain. When working with data from various…]]></description><link>https://swiftuicentral.com/swiftui-decoupling-models</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-decoupling-models</guid><category><![CDATA[SwiftUI]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[decoupling]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Wed, 13 Sep 2023 11:10:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/kn-UmDZQDjM/upload/2b14d9db6aa7e8b00a49d8863e57c422.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem"><strong>Problem:</strong></h2>
<p>How can we avoid breaking an entire app when a model changes?</p>
<h2 id="heading-solution"><strong>Solution:</strong></h2>
<p>Decouple each model based on their specific domain.</p>
<hr />
<h3 id="heading-a-deeper-dive"><strong>A Deeper Dive</strong></h3>
<p>When working with data from various sources, a common challenge developers face is the potential for entire sections of an app to break when there's a minor model change. A robust solution to this problem is decoupling models based on their specific domains.</p>
<h2 id="heading-models">Models</h2>
<p>Here we will represent the user model in 3 different ways:</p>
<ol>
<li><p><strong>UserApiV2</strong> - Represents our data source's structure from an API.</p>
</li>
<li><p><strong>User</strong> - Acts as an intermediary and generic model, used in the entire app.</p>
</li>
<li><p><strong>UserViewData</strong> - Transforms and formats data for SwiftUI view representation.</p>
</li>
</ol>
<hr />
<h3 id="heading-models-definition">Models definition</h3>
<p>Let's get started creating the <code>UserApiV2</code> will represent the API model</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">UserApiV2</span>: <span class="hljs-title">Codable</span> </span>{ <span class="hljs-comment">// 1</span>
  <span class="hljs-keyword">let</span> id: <span class="hljs-type">Int</span>
  <span class="hljs-keyword">let</span> firstName: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> lastName: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> dob: <span class="hljs-type">String</span> <span class="hljs-comment">// ISO8601 format</span>
  <span class="hljs-keyword">let</span> phoneNumber: <span class="hljs-type">PhoneApiV2</span>
  <span class="hljs-keyword">let</span> address: <span class="hljs-type">AddressApiV2</span>
  <span class="hljs-keyword">let</span> email: <span class="hljs-type">String</span>

  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PhoneApiV2</span>: <span class="hljs-title">Codable</span> </span>{ <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> countryPrefix: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> number: <span class="hljs-type">String</span>
  }

  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">AddressApiV2</span>: <span class="hljs-title">Codable</span> </span>{ <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> street: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> city: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> state: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> postalCode: <span class="hljs-type">String</span>
  }
}
</code></pre>
<ol>
<li>You notice here that all objects are conforming to the <code>Codable</code> protocol because this is a requirement that will allow us to encode/decode objects.<br /> The good thing here to notice is that this <code>Codable</code> conformance is an implementation detail from the API side that will not pollute other user objects.</li>
</ol>
<p>Now create the <code>User</code> object that will be used everywhere in the app</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">let</span> id: <span class="hljs-type">Int</span>
  <span class="hljs-keyword">let</span> firstName: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> lastName: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> dob: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> phoneNumber: <span class="hljs-type">Phone</span>
  <span class="hljs-keyword">let</span> address: <span class="hljs-type">Address</span>
  <span class="hljs-keyword">let</span> email: <span class="hljs-type">String</span>

  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Phone</span> </span>{
    <span class="hljs-keyword">let</span> countryPrefix: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> number: <span class="hljs-type">String</span>
  }

  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Address</span> </span>{
    <span class="hljs-keyword">let</span> street: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> city: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> state: <span class="hljs-type">String</span>
    <span class="hljs-keyword">let</span> postalCode: <span class="hljs-type">String</span>
  }
}
</code></pre>
<ul>
<li><p>The important thing to note here is that no more <code>Codable</code> conformance and it's a good point, we don't want to leak implementation details from infrastructure (API, database, ...) in our model app.</p>
</li>
<li><p>The <code>User</code> object keeps the same property name but feel free you change it if you want.</p>
</li>
<li><p>The <code>User</code> object keeps the same object structure but you can adapt it as you want.</p>
</li>
<li><p>The <code>User</code> object keeps all properties of the <code>UserApiV2</code> object, because it needs them all (but if some are not neccessary you can omit them and come back later to add them if needed).</p>
</li>
<li><p>So this <code>User</code> model is the model of your app, It belongs to you and is your responsibility to shape it as you want it to be.</p>
</li>
</ul>
<p>Now create the <code>UserViewData</code> model that will be used in the SwiftUI view.</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">UserViewData</span> </span>{
  <span class="hljs-keyword">let</span> name: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> birthDate: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> phoneNumber: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> address: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> email: <span class="hljs-type">String</span>
}
</code></pre>
<ul>
<li>This model doesn't contain any logic, it just displays already formatted data that are required for the design.<br />  This is for this reason that all properties are of type <code>String</code></li>
</ul>
<hr />
<h3 id="heading-load-user-interface">Load User interface</h3>
<p>First I will create an interface <code>UserLoading</code> that will abstract the <code>User</code> load using <code>protocol</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">UserLoading</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetchUser</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; <span class="hljs-type">User</span>
}
</code></pre>
<ul>
<li>We will always use this interface to fetch the user, which allows us to use different implementations (API, database, ...)</li>
</ul>
<hr />
<h2 id="heading-models-creation">Models creation</h2>
<h3 id="heading-create-userapiv2-model">Create <code>UserApiV2</code> model</h3>
<p>Now we need to create the <code>UserApiV2</code> model.<br />We will mock the backend response using a local <strong>JSON</strong></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MockUrlSessionUserLoading</span>: <span class="hljs-title">UserLoading</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; <span class="hljs-type">User</span> {
    <span class="hljs-keyword">let</span> url = <span class="hljs-type">Bundle</span>.main.url(forResource: <span class="hljs-string">"user"</span>, withExtension: <span class="hljs-string">"json"</span>)! <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">try</span> <span class="hljs-type">Data</span>(contentsOf: url)
    <span class="hljs-keyword">let</span> userApiV2 = <span class="hljs-keyword">try</span> <span class="hljs-type">JSONDecoder</span>().decode(<span class="hljs-type">UserApiV2</span>.<span class="hljs-keyword">self</span>, from: data) 
    <span class="hljs-keyword">return</span> userApiV2.toUser() <span class="hljs-comment">// 2</span>
  }
}
</code></pre>
<ol>
<li><p>We need to create the <strong>JSON</strong> file <strong>user.json</strong> that be read locally.</p>
</li>
<li><p>We must create the <code>toUser()</code> function that will convert the <code>UserApiV2</code> object to the <code>User</code> object we want to return.</p>
</li>
</ol>
<p>Start creating the <strong>user.json</strong> file<br />Create a new file<br />In the <strong>Other</strong> section choose <strong>Empty</strong> and call it <strong>user.json</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694517013915/904dc571-a505-4554-a958-675b5a2aeea7.png" alt class="image--center mx-auto" /></p>
<p>In the <strong>user.json</strong> copy and paste this code:</p>
<pre><code class="lang-plaintext">{
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "dob": "2023-09-10T10:00:00Z",
    "phoneNumber": {
        "countryPrefix": "+1",
        "number": "1234567890"
    },
    "address": {
        "street": "123 Apple St.",
        "city": "Cupertino",
        "state": "CA",
        "postalCode": "95014"
    },
    "email": "john.doe@example.com"
}
</code></pre>
<p>Now create the <code>toUser()</code> function that will be an extension of the <code>UserApiV2</code> type</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">UserApiV2</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">toUser</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">User</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-type">User</span>(
      id: <span class="hljs-keyword">self</span>.id,
      firstName: <span class="hljs-keyword">self</span>.firstName,
      lastName: <span class="hljs-keyword">self</span>.lastName,
      dob: <span class="hljs-keyword">self</span>.dob,
      phoneNumber: .<span class="hljs-keyword">init</span>(
        countryPrefix: <span class="hljs-keyword">self</span>.phoneNumber.countryPrefix,
        number: <span class="hljs-keyword">self</span>.phoneNumber.number
      ),
      address: .<span class="hljs-keyword">init</span>(
        street: <span class="hljs-keyword">self</span>.address.street,
        city: <span class="hljs-keyword">self</span>.address.city,
        state: <span class="hljs-keyword">self</span>.address.state,
        postalCode: <span class="hljs-keyword">self</span>.address.postalCode
      ),
      email: <span class="hljs-keyword">self</span>.email
    )
  }
}
</code></pre>
<ul>
<li>Here conversion is very straightforward, all the properties are identical (that is not always the case)</li>
</ul>
<hr />
<h2 id="heading-viewmodel-creation">ViewModel creation</h2>
<p>Let's create the view model that will be injected into the SwiftUI view</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> userViewData = emptyUserViewData()

  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> userLoader: <span class="hljs-type">UserLoading</span>

  <span class="hljs-keyword">init</span>(userLoader: <span class="hljs-type">UserLoading</span>) { <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">self</span>.userLoader = userLoader
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span> {
    <span class="hljs-type">Task</span> {
      <span class="hljs-keyword">do</span> {
        <span class="hljs-keyword">let</span> user = <span class="hljs-keyword">try</span> await userLoader.getUser() <span class="hljs-comment">// 2</span>
        userViewData = user.toUserViewData() <span class="hljs-comment">// 3</span>
      } <span class="hljs-keyword">catch</span> {
        <span class="hljs-comment">// Handle any errors</span>
      }
    }
  }
}

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">emptyUserViewData</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UserViewData</span> {
    <span class="hljs-type">UserViewData</span>(name: <span class="hljs-string">""</span>, birthDate: <span class="hljs-string">""</span>, phoneNumber: <span class="hljs-string">""</span>, address: <span class="hljs-string">""</span>, email: <span class="hljs-string">""</span>)
}
</code></pre>
<ol>
<li><p>I use dependency injection to use the <code>UserLoading</code> .</p>
</li>
<li><p>I get the user from the <code>userLoader</code> via the <code>getUser()</code> function defined in the interface.</p>
</li>
<li><p>I converted the <code>User</code> object to the <code>UserViewData</code> object to be able to update the UI using the <code>toUserViewData()</code> function.</p>
</li>
</ol>
<p>Create the <code>toUserViewData()</code> function using <code>extension</code> on the <code>User</code> object</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">toUserViewData</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">UserViewData</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-type">UserViewData</span>(
      name: <span class="hljs-string">"\(self.firstName) \(self.lastName)"</span>, <span class="hljs-comment">// 1</span>
      birthDate: <span class="hljs-type">DateFormatter</span>.displayDateFormatter.string(from: <span class="hljs-type">ISO8601DateFormatter</span>().date(from: <span class="hljs-keyword">self</span>.dob) ?? <span class="hljs-type">Date</span>()), <span class="hljs-comment">// 2</span>
      phoneNumber: <span class="hljs-string">"\(self.phoneNumber.countryPrefix) \(self.phoneNumber.number)"</span>, <span class="hljs-comment">// 3</span>
      address: <span class="hljs-string">"\(self.address.street)\n\(self.address.city), \(self.address.state) \(self.address.postalCode)"</span>, <span class="hljs-comment">// 4</span>
      email: <span class="hljs-keyword">self</span>.email
    )
  }
}

<span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">DateFormatter</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">let</span> displayDateFormatter: <span class="hljs-type">DateFormatter</span> = {
    <span class="hljs-keyword">let</span> formatter = <span class="hljs-type">DateFormatter</span>()
    formatter.dateStyle = .medium
    <span class="hljs-keyword">return</span> formatter
  }()
}
</code></pre>
<ol>
<li><p>For the name, I group the first and last name.</p>
</li>
<li><p>The date is transformed into a readable format.</p>
</li>
<li><p>The phone number is composed using the country prefix and number.</p>
</li>
<li><p>The address is created with street, city, state and postal code and returned to the line when needed.</p>
</li>
</ol>
<p>The UI will update every time this model changes</p>
<hr />
<h2 id="heading-view-creation">View Creation</h2>
<p>Create the <code>UserView</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">UserView</span>: <span class="hljs-title">View</span> </span>{
  @<span class="hljs-type">ObservedObject</span> <span class="hljs-keyword">var</span> viewModel: <span class="hljs-type">UserViewModel</span>

  <span class="hljs-keyword">var</span> body: some <span class="hljs-type">View</span> {
    <span class="hljs-type">Form</span> {
      <span class="hljs-type">Text</span>(viewModel.userViewData.name) <span class="hljs-comment">// 1</span>
      <span class="hljs-type">Text</span>(viewModel.userViewData.birthDate) <span class="hljs-comment">// 1</span>
      <span class="hljs-type">Text</span>(viewModel.userViewData.phoneNumber) <span class="hljs-comment">// 1</span>
      <span class="hljs-type">Text</span>(viewModel.userViewData.address) <span class="hljs-comment">// 1</span>
      <span class="hljs-type">Text</span>(viewModel.userViewData.email) <span class="hljs-comment">// 1</span>
    }
    .onAppear {
      viewModel.getUser()
    }
  }
}
</code></pre>
<ol>
<li>This is very simple, not need to handle the logic in the SwiftUI view, the heavy work has been already done. It just needs to render the view with the provided formatted data.</li>
</ol>
<p>Let's create a preview to see if everything is working fine:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">UserView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-keyword">let</span> userLoader = <span class="hljs-type">MockUrlSessionUserLoading</span>()
    <span class="hljs-keyword">let</span> viewModel = <span class="hljs-type">UserViewModel</span>(userLoader: userLoader)
    <span class="hljs-type">UserView</span>(viewModel: viewModel)
  }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694519156781/0bdabf9f-c099-44ab-961c-9c070d3298f6.png" alt class="image--center mx-auto" /></p>
<p>The UI rendered as expected everything is working fine</p>
<hr />
<p>Now we will expend the problem and imagine you have a new requirement:</p>
<p><strong>"The cached user must be used in the remote get failed"</strong></p>
<p>We now potentially use a model that has been used for the persistence of the <code>User</code><br />We use <strong>Realm</strong> here to demonstrate the benefit of decoupling our model</p>
<h2 id="heading-create-userrealm-model">Create UserRealm model</h2>
<p>Start by creating all the types required to be able to persist the model <code>UserRealm</code>, <code>PhoneRealm</code> and <code>AdressRealm</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRealm</span>: <span class="hljs-title">Object</span> </span>{
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> id: <span class="hljs-type">Int</span> = <span class="hljs-number">0</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> firstName: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> lastName: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> dob: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> phone: <span class="hljs-type">PhoneRealm?</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> address: <span class="hljs-type">AddressRealm?</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> emailAddress: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>

  <span class="hljs-keyword">convenience</span> <span class="hljs-keyword">init</span>(id: <span class="hljs-type">Int</span>, firstName: <span class="hljs-type">String</span>, lastName: <span class="hljs-type">String</span>, dob: <span class="hljs-type">String</span>, phone: <span class="hljs-type">PhoneRealm</span>, address: <span class="hljs-type">AddressRealm</span>, emailAddress: <span class="hljs-type">String</span>) {
    <span class="hljs-keyword">self</span>.<span class="hljs-keyword">init</span>()
    <span class="hljs-keyword">self</span>.id = id
    <span class="hljs-keyword">self</span>.firstName = firstName
    <span class="hljs-keyword">self</span>.lastName = lastName
    <span class="hljs-keyword">self</span>.dob = dob
    <span class="hljs-keyword">self</span>.phone = phone
    <span class="hljs-keyword">self</span>.address = address
    <span class="hljs-keyword">self</span>.emailAddress = emailAddress
  }

  <span class="hljs-keyword">required</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">init</span>() {
    <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PhoneRealm</span>: <span class="hljs-title">Object</span> </span>{
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> countryPrefix: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> number: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>

  <span class="hljs-keyword">convenience</span> <span class="hljs-keyword">init</span>(countryPrefix: <span class="hljs-type">String</span>, number: <span class="hljs-type">String</span>) {
    <span class="hljs-keyword">self</span>.<span class="hljs-keyword">init</span>()
    <span class="hljs-keyword">self</span>.countryPrefix = countryPrefix
    <span class="hljs-keyword">self</span>.number = number
  }

  <span class="hljs-keyword">required</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">init</span>() {
    <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddressRealm</span>: <span class="hljs-title">Object</span> </span>{
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> street: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> city: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> state: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>
  <span class="hljs-meta">@objc</span> <span class="hljs-keyword">dynamic</span> <span class="hljs-keyword">var</span> postalCode: <span class="hljs-type">String</span> = <span class="hljs-string">""</span>

  <span class="hljs-keyword">convenience</span> <span class="hljs-keyword">init</span>(street: <span class="hljs-type">String</span>, city: <span class="hljs-type">String</span>, state: <span class="hljs-type">String</span>, postalCode: <span class="hljs-type">String</span>) {
    <span class="hljs-keyword">self</span>.<span class="hljs-keyword">init</span>()
    <span class="hljs-keyword">self</span>.street = street
    <span class="hljs-keyword">self</span>.city = city
    <span class="hljs-keyword">self</span>.state = state
    <span class="hljs-keyword">self</span>.postalCode = postalCode
  }

  <span class="hljs-keyword">required</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">init</span>() {
    <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
  }
}
</code></pre>
<p>We also need to create the <code>extension</code> that will allow us to convert <code>UserRealm</code> to <code>User</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">UserRealm</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">toUser</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">User</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-type">User</span>(
      id: <span class="hljs-keyword">self</span>.id,
      firstName: <span class="hljs-keyword">self</span>.firstName,
      lastName: <span class="hljs-keyword">self</span>.lastName,
      dob: <span class="hljs-keyword">self</span>.dob,
      phoneNumber: <span class="hljs-type">User</span>.<span class="hljs-type">Phone</span>(
        countryPrefix: <span class="hljs-keyword">self</span>.phone?.countryPrefix ?? <span class="hljs-string">""</span>,
        number: <span class="hljs-keyword">self</span>.phone?.number ?? <span class="hljs-string">""</span>
      ),
      address: <span class="hljs-type">User</span>.<span class="hljs-type">Address</span>(
        street: <span class="hljs-keyword">self</span>.address?.street ?? <span class="hljs-string">""</span>,
        city: <span class="hljs-keyword">self</span>.address?.city ?? <span class="hljs-string">""</span>,
        state: <span class="hljs-keyword">self</span>.address?.state ?? <span class="hljs-string">""</span>,
        postalCode: <span class="hljs-keyword">self</span>.address?.postalCode ?? <span class="hljs-string">""</span>
      ),
      email: <span class="hljs-keyword">self</span>.emailAddress
    )
  }
}
</code></pre>
<p>Create the <code>MockRealmUserLoading</code> will fake the query in the database</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MockRealmUserLoading</span>: <span class="hljs-title">UserLoading</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; <span class="hljs-type">User</span> {
    <span class="hljs-keyword">let</span> mockPhone = <span class="hljs-type">PhoneRealm</span>(countryPrefix: <span class="hljs-string">"+1"</span>, number: <span class="hljs-string">"1234567890"</span>)
    <span class="hljs-keyword">let</span> mockAddress = <span class="hljs-type">AddressRealm</span>(street: <span class="hljs-string">"123 Apple St"</span>, city: <span class="hljs-string">"Tech Town"</span>, state: <span class="hljs-string">"Silicon Valley"</span>, postalCode: <span class="hljs-string">"95014"</span>)
    <span class="hljs-keyword">let</span> mockRealmUser = <span class="hljs-type">UserRealm</span>(id: <span class="hljs-number">1</span>, firstName: <span class="hljs-string">"John"</span>, lastName: <span class="hljs-string">"Doe"</span>, dob: <span class="hljs-string">"1990-01-01T00:00:00Z"</span>, phone: mockPhone, address: mockAddress, emailAddress: <span class="hljs-string">"john.doe@example.com"</span>)

    <span class="hljs-keyword">return</span> mockRealmUser.toUser()
  }
}
</code></pre>
<p>Now the requirement is to start from remote and if failed return the user locally<br />We can create a new object <code>RemoteUserLoadingWithLocalFallback</code> that will compose those types:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RemoteUserLoadingWithLocalFallback</span>: <span class="hljs-title">UserLoading</span> </span>{
  <span class="hljs-keyword">let</span> primary: <span class="hljs-type">UserLoading</span>
  <span class="hljs-keyword">let</span> secondary: <span class="hljs-type">UserLoading</span>

  <span class="hljs-keyword">init</span>(primary: <span class="hljs-type">UserLoading</span>, secondary: <span class="hljs-type">UserLoading</span>) {
    <span class="hljs-keyword">self</span>.primary = primary
    <span class="hljs-keyword">self</span>.secondary = secondary
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; <span class="hljs-type">User</span> {
    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> await primary.getUser()
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> await secondary.getUser()
    }
  }
}
</code></pre>
<p>The app still compiles.<br />The live preview still works when updating the composition using the <code>RemoteUserLoadingWithLocalFallback</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">UserView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-keyword">let</span> userRemoteLoader = <span class="hljs-type">MockUrlSessionUserLoading</span>()
    <span class="hljs-keyword">let</span> userLocalLoader = <span class="hljs-type">MockRealmUserLoading</span>()
    <span class="hljs-keyword">let</span> userLoader = <span class="hljs-type">RemoteUserLoadingWithLocalFallback</span>(
      primary: userRemoteLoader,
      secondary: userLocalLoader
    )
    <span class="hljs-keyword">let</span> viewModel = <span class="hljs-type">UserViewModel</span>(userLoader: userLoader)
    <span class="hljs-type">UserView</span>(viewModel: viewModel)
  }
}
</code></pre>
<p>Of course, you can decide to replace frameworks:<br /><strong>URLSession -&gt; Alamofire</strong><br /><strong>Realm -&gt; CoreData</strong><br />You just need to create new types <code>AlamofireUserLoading</code> and <code>CoreDataUserLoading</code> that will conform to the <code>UserLoading</code> interface and injecting those new types will be an easy change because the entire app is not coupled with any framework, they are just details of the implementation</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope that you enjoy the power of the domain-specific model.<br />Through domain-specific modeling (<code>UserAPIV2</code>, <code>UserRealm</code>), we have created a flexible structure that not only preserves the integrity of our SwiftUI app (<code>User</code>) but also makes it adaptable to different data sources (<code>UserDataView</code>).<br />Whether we're fetching data from an API or a local Realm database, the foundation remains unaffected.<br />This modular approach ensures that our app can scale with changing requirements without significant refactoring, ensuring a robust and resilient architecture.</p>
<p>That's it !! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - TDD actor to avoid race condition]]></title><description><![CDATA[Code that runs synchronously is easy to manage and understandBut when start introducing threads, problems occurYou need to manage access to the read/write…]]></description><link>https://swiftuicentral.com/swiftui-tdd-actor-to-avoid-race-condition</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-tdd-actor-to-avoid-race-condition</guid><category><![CDATA[actor]]></category><category><![CDATA[SwiftUI]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[race-condition]]></category><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Thu, 12 Jan 2023 12:27:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/DGsqL2j028E/upload/e51e5a7dd6631367a733ec95cd5625ed.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-to-avoid-threading-race-conditions-in-your-class">Problem: How to avoid threading race conditions in your class?</h2>
<h3 id="heading-solution-use-actor-that-handles-all-the-concurrency-for-you">Solution: Use actor that handles all the concurrency for you!</h3>
<p>Code that runs synchronously is easy to manage and understand<br />But when start introducing threads, problems occur<br />You need to manage access to the read/write of a property<br />Using a serial queue to avoid race condition</p>
<p>But with <code>actor</code> this will be a lot more simple<br />It handles all concurrency for you 🤩</p>
<hr />
<p>We use Unit Test to prove that everything is working fine</p>
<hr />
<p>First, create a simple <code>Contact</code> model<br />It will be used for read/write operation in memory</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Contact</span>: <span class="hljs-title">Equatable</span> </span>{
  <span class="hljs-keyword">let</span> id = <span class="hljs-type">UUID</span>().uuidString
  <span class="hljs-keyword">let</span> name: <span class="hljs-type">String</span>
}
</code></pre>
<hr />
<p>Create a simple class <code>ContactCache</code><br />It will synchronously read/write contacts in memory</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ContactCache</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> dictContacts = [<span class="hljs-type">String</span>: <span class="hljs-type">Contact</span>]()

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">save</span><span class="hljs-params">(<span class="hljs-number">_</span> contact: Contact)</span></span> {
    dictContacts[contact.id] = contact
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(<span class="hljs-number">_</span> contact: Contact)</span></span> -&gt; <span class="hljs-type">Contact?</span> {
    dictContacts[contact.id]
  }
}
</code></pre>
<hr />
<p>Write a test that will save and load a contact</p>
<pre><code class="lang-swift"><span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActorTests</span>: <span class="hljs-title">XCTestCase</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_save_saveContactInCache</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> contact = <span class="hljs-type">Contact</span>(name: <span class="hljs-string">"A name"</span>)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">ContactCache</span>()

    sut.save(contact)
    <span class="hljs-keyword">let</span> contactCache = sut.load(contact)

    <span class="hljs-type">XCTAssertEqual</span>(contactCache, contact)
  }
}
</code></pre>
<p>Run the test and it passes<br />With synchronous behavior everything is working fine<br />Now introduce some concurrency using the <code>global()</code> queue</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ContactCache</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> dictContacts = [<span class="hljs-type">String</span>: <span class="hljs-type">Contact</span>]()

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">save</span><span class="hljs-params">(<span class="hljs-number">_</span> contact: Contact)</span></span> {
    <span class="hljs-type">DispatchQueue</span>.global().async { <span class="hljs-comment">// 1</span>
      <span class="hljs-keyword">self</span>.dictContacts[contact.id] = contact
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(<span class="hljs-number">_</span> contactId: String, completion: @escaping <span class="hljs-params">(Contact?)</span></span></span> -&gt; <span class="hljs-type">Void</span>) { <span class="hljs-comment">// 2</span>
    <span class="hljs-type">DispatchQueue</span>.global().async { <span class="hljs-comment">// 1</span>
      completion(<span class="hljs-keyword">self</span>.dictContacts[contactId])
    }
  }
}
</code></pre>
<ol>
<li><p>Dispatch the read/write operation to the <code>global</code> queue to avoid to block the main thread</p>
</li>
<li><p>Unfortunately, we need to add a completion handler to return the result when the operation is finished, which complicates our code</p>
</li>
</ol>
<p>Now update the test:</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_save_saveContactInCache</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> contact = <span class="hljs-type">Contact</span>(name: <span class="hljs-string">"A name"</span>)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">ContactCache</span>()

    sut.save(contact)

    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect that load completes"</span>)
    <span class="hljs-keyword">var</span> contactCache: <span class="hljs-type">Contact?</span>
    sut.load(contact.id) { contact <span class="hljs-keyword">in</span>
      contactCache = contact
      exp.fulfill()
    }

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">0.1</span>) <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertEqual</span>(contactCache, contact)
  }
</code></pre>
<ol>
<li>We need to wait for load completion</li>
</ol>
<p>Run the test and it fails with a crash<br /><em>Thread 7: EXC_BAD_ACCESS (code=1, address=0x18)</em><br />The thread 7 is a concurrent queue<br />We try to load contact during the save operation so the app crashed</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673473230674/c570d81f-325a-43f1-88ef-ab8874195ede.png" alt class="image--center mx-auto" /></p>
<p>To make the test pass we need to protect read/write operations<br />Using a serial queue</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ContactCache</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> dictContacts = [<span class="hljs-type">String</span>: <span class="hljs-type">Contact</span>]()
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> serialQueue = <span class="hljs-type">DispatchQueue</span>(label: <span class="hljs-string">"contact.cache"</span>) <span class="hljs-comment">// 1</span>

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">save</span><span class="hljs-params">(<span class="hljs-number">_</span> contact: Contact)</span></span> {
    <span class="hljs-type">DispatchQueue</span>.global().async { 
      <span class="hljs-keyword">self</span>.serialQueue.async { <span class="hljs-comment">// 2</span>
        <span class="hljs-keyword">self</span>.dictContacts[contact.id] = contact
      }
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(<span class="hljs-number">_</span> contactId: String, completion: @escaping <span class="hljs-params">(Contact?)</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    <span class="hljs-type">DispatchQueue</span>.global().async {
      <span class="hljs-keyword">self</span>.serialQueue.async { <span class="hljs-comment">// 2</span>
        completion(<span class="hljs-keyword">self</span>.dictContacts[contactId])
      }
    }
  }
}
</code></pre>
<ol>
<li><p>Create a <code>DispatchQueue</code> that is serial by default so the code inside it will run synchronously</p>
</li>
<li><p>Make read/write operations in the <code>serialQueue</code> so if the save operation is running, the load operation has to wait until the end of it</p>
</li>
</ol>
<p>Run the tests as many times as you want<br />They always pass</p>
<p>Ok good but this class now looks a bit messy</p>
<ol>
<li><p>We need to add global queues everywhere</p>
</li>
<li><p>We need to add a completion handler to the <code>load()</code> function</p>
</li>
<li><p>We need to handle manually the synchronous behavior of this class</p>
</li>
</ol>
<p>Because of this mess, it's time for the <code>actor</code> to comes in</p>
<hr />
<p>Start by deleting all the <code>global()</code> queues and also the <code>serialQueue</code><br />Replace the <code>class</code> keyword by <code>actor</code></p>
<pre><code class="lang-swift">actor <span class="hljs-type">ContactCache</span> { <span class="hljs-comment">// 1</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> dictContacts = [<span class="hljs-type">String</span>: <span class="hljs-type">Contact</span>]()

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">save</span><span class="hljs-params">(<span class="hljs-number">_</span> contact: Contact)</span></span> {
    <span class="hljs-keyword">self</span>.dictContacts[contact.id] = contact
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(<span class="hljs-number">_</span> contactId: String)</span></span> -&gt; <span class="hljs-type">Contact?</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>.dictContacts[contactId]
  }
}
</code></pre>
<ol>
<li>The <code>class</code> keyword has been replaced by the <code>actor</code> keyword. Now all functions will behave like <code>async</code> function</li>
</ol>
<p>Update also the test, deleting the completion handler and the expectation</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_save_saveContactInCache</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> contact = <span class="hljs-type">Contact</span>(name: <span class="hljs-string">"A name"</span>)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">ContactCache</span>()

    sut.save(contact) <span class="hljs-comment">// 1</span>

    <span class="hljs-keyword">let</span> contactCache = sut.load(contact.id) <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertEqual</span>(contactCache, contact)
  }
</code></pre>
<ol>
<li><p>Compiler help guide us with errors:<br /> <em>Actor-isolated instance method 'save' can not be referenced from a non-isolated context</em></p>
<p> and<br /> <em>Actor-isolated instance method 'load' can not be referenced from a non-isolated context</em></p>
</li>
</ol>
<p>We need to use actor functions like <code>async/await</code></p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_save_saveContactInCache</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> contact = <span class="hljs-type">Contact</span>(name: <span class="hljs-string">"A name"</span>)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">ContactCache</span>()

    <span class="hljs-type">Task</span> { <span class="hljs-comment">// 1</span>
      await sut.save(contact) <span class="hljs-comment">// 2</span>
    }

    <span class="hljs-type">Task</span> { <span class="hljs-comment">// 1</span>
      <span class="hljs-keyword">let</span> contactCache = await sut.load(contact.id) <span class="hljs-comment">// 2</span>
      <span class="hljs-type">XCTAssertEqual</span>(contactCache, contact)
    }
  }
</code></pre>
<ol>
<li><p>Encapsulate the logic of functions into a <code>Task</code></p>
</li>
<li><p>Add the <code>await</code> keyword because they are now <code>async</code> functions</p>
</li>
</ol>
<p>You can run the test and it passes as much as you want the will always pass<br />The <code>load()</code> function will always wait that the <code>save()</code> function completes</p>
<hr />
<p>The <code>actor</code> feature helps a lot to deal with all concurrency problems<br />Eliminating global/serial queues and completion callback hell<br />Also, avoid a lot of crashes and future complicated debug sessions<br />I hope you enjoy this journey with <code>actor</code> and you will use it in your project</p>
<p>That's it !! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - TDD async/await]]></title><description><![CDATA[IMPORTANT: This tutorial is only available for iOS 15+It will use the async/await integration in URLSessionAnd the AsyncImage SwiftUI view to load the…]]></description><link>https://swiftuicentral.com/swiftui-tdd-asyncawait</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-tdd-asyncawait</guid><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[SwiftUI]]></category><category><![CDATA[Swift]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Thu, 13 Oct 2022 11:00:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/1k3vsv7iIIc/upload/v1665658899515/Y-Y5mC9aRe.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-to-tdd-asyncawait">Problem: How to TDD async/await ?</h2>
<h3 id="heading-solution-stub-the-response-async-function-needs-to-know-its-result-before-call">Solution: Stub the response, async function needs to know it's result before call</h3>
<p>IMPORTANT: This tutorial is only available for iOS 15+<br />It will use the async/await integration in <code>URLSession</code><br />And the <code>AsyncImage</code> SwiftUI view to load the image  </p>
<p>async/await it new to the in iOS ecosystem<br />Will learn here how to TDD it  </p>
<p>Will use the Dog API to test our logic<br />It's a simple API no need for private key<br />First we will get dogs form the API<br />Second download dogs images from returned image url response.  </p>
<p>Here is the result of our implementation<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1664828478716/s-ct4_J5d.png" alt="image.png" /></p>
<hr />
<p>First the list of behaviour to test</p>
<pre>
 ======= LOAD DOGS
[ ] On init view model, status is idle
[ ] On load use the dog API url to get dogs images
[ ] Load dogs update status to loading
    [ ] If Load dogs failed delivers .connectivity error
      [ ] Display an error message (text)
      [ ] User can retry to load (button)
    [ ] Load dogs succeed with 200 response
      [ ] Parsing succeed delivers dogs
      [ ] Extract dogs names from returned url
      [ ] Parsing failed delivers .invalidData error
        [ ] Display an error message (text)
        [ ] User can retry to load (button)
</pre>

<hr />
<p>Start with this first requirement<br />It ensure that nothing happen on start  </p>
<pre>
 ======= LOAD DOGS
[ ] On init view model, status is idle
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_init_statusIdle</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">DogsViewModel</span>()

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, .idle)
  }
</code></pre>
<ol>
<li>Need to create the <code>DogsViewModel</code></li>
<li>Need to create the status enum and variable </li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span> </span>{ 
    <span class="hljs-keyword">case</span> idle
  }

  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> status = <span class="hljs-type">Status</span>.idle
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
[✅] On init view model, status is idle
</pre>

<hr />
<p>Continue with this requirement for  </p>
<pre>
 ========= LOAD DOGS
[ ] On load use the dog API url to get dogs images
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadDogs_performARequestWithDogsURLRequest</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> dogsURLRequest = <span class="hljs-type">URLRequest</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://dog.ceo/api/breeds/image/random/3"</span>)!) <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> urlSessionSpy = <span class="hljs-type">URLSessionAsyncAwaitSpy</span>(result: .failure(.connectivity)) <span class="hljs-comment">// 2</span>
    <span class="hljs-keyword">let</span> networkService = <span class="hljs-type">NetworkService</span>(session: urlSessionSpy) <span class="hljs-comment">// 3</span>
    <span class="hljs-keyword">let</span> dogServiceSpy = <span class="hljs-type">DogService</span>(networkService: networkService) <span class="hljs-comment">// 4</span>
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">DogViewModelSpy</span>(dogService: dogServiceSpy) <span class="hljs-comment">// 5</span>

    <span class="hljs-keyword">try</span>? await sut.loadDogs() <span class="hljs-comment">// 6</span>

    <span class="hljs-type">XCTAssertEqual</span>(urlSessionSpy.requests, [dogsURLRequest]) <span class="hljs-comment">// 7</span>
  }
</code></pre>
<ol>
<li>Url that returns 3 dogs in a random order. </li>
<li>First we need to create a spy that will use our mock of the URLSession async function. We inject (stub) the response of API (need to complete with error or success. The function must complete or you will be blocked be the <code>await</code> that will never return).  </li>
<li>The <code>NetworkService</code> will request dogs to the API and will return response as <code>Data</code>. We inject our <code>urlSessionSpy</code> to able to control the result.</li>
<li>The <code>DogService</code> will turn <code>Data</code> into a rich model dogs</li>
<li>The <code>DogViewModel</code> will use the service to get dogs</li>
<li>Use the SUT that perform an async loading of dogs waiting for the response</li>
<li>After load complete, check that the right URL has been used</li>
</ol>
<p>First we need a mock to test the <code>URLSession</code><br />For this async function<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1664912844154/Yu1Q7kMII.png" alt="image.png" /></p>
<p>Start creating the <code>protocol</code><br />It that looks like the signature of this function  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">AsyncAwait</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">data</span><span class="hljs-params">(request: URLRequest)</span></span> async <span class="hljs-keyword">throws</span> -&gt; (<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>)
}
</code></pre>
<p>Implement the mock to <code>URLSession</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">URLSession</span>: <span class="hljs-title">AsyncAwait</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">data</span><span class="hljs-params">(request: URLRequest)</span></span> async <span class="hljs-keyword">throws</span> -&gt; (<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>) {
        <span class="hljs-keyword">try</span> await <span class="hljs-keyword">self</span>.data(<span class="hljs-keyword">for</span>: request)
    }
}
</code></pre>
<p>We can now create <code>URLSessionAsyncAwaitSpy</code>  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">URLSessionAsyncAwaitSpy</span>: <span class="hljs-title">AsyncAwait</span> </span>{
    <span class="hljs-keyword">var</span> requests = [<span class="hljs-type">URLRequest</span>]()
    <span class="hljs-keyword">let</span> result: <span class="hljs-type">Result</span>&lt;(<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>), <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>&gt;

    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">init</span>(result: <span class="hljs-type">Result</span>&lt;(<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>), <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>&gt;) {
      <span class="hljs-keyword">self</span>.result = result
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">data</span><span class="hljs-params">(request: URLRequest)</span></span> async <span class="hljs-keyword">throws</span> -&gt; (<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>) {
      <span class="hljs-keyword">self</span>.requests.append(request) <span class="hljs-comment">// 1</span>
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> result.<span class="hljs-keyword">get</span>() <span class="hljs-comment">// 2</span>
    }
  }
</code></pre>
<ol>
<li>We accumulate all requests for this function calls (Spy)</li>
<li>We return the result that was injected (Stub)</li>
</ol>
<p>Second create the <code>NetworkService</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NetworkService</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> session: <span class="hljs-type">AsyncAwait</span>

  <span class="hljs-keyword">init</span>(session: <span class="hljs-type">AsyncAwait</span> = <span class="hljs-type">URLSession</span>.shared) {
    <span class="hljs-keyword">self</span>.session = session
  }

  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Error</span>: <span class="hljs-title">Swift</span>.<span class="hljs-title">Error</span> </span>{
    <span class="hljs-keyword">case</span> connectivity
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">perform</span><span class="hljs-params">(request: URLRequest)</span></span> async <span class="hljs-keyword">throws</span> -&gt; (<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>) {
    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">let</span> (data, response) = <span class="hljs-keyword">try</span> await session.data(request: request)
      <span class="hljs-keyword">return</span> (data, response)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-keyword">throw</span> error
    }
  }
}
</code></pre>
<p>Third create the <code>DogService</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogService</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> networkService: <span class="hljs-type">NetworkService</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> loadDogsRequest = <span class="hljs-type">URLRequest</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://any-url.com"</span>)!) <span class="hljs-comment">// 1</span>

  <span class="hljs-keyword">init</span>(networkService: <span class="hljs-type">NetworkService</span>) {
    <span class="hljs-keyword">self</span>.networkService = networkService
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">do</span> {
      <span class="hljs-number">_</span> = <span class="hljs-keyword">try</span> await networkService.perform(request: loadDogsRequest)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-keyword">throw</span> error
    }
  }
}
</code></pre>
<ol>
<li>Enter a wrong URL to see a failed test first</li>
</ol>
<p>Fourth update <code>DogsViewModel</code> injecting the <code>DogService</code> and create the <code>loadDogs()</code> async function</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> dogService: <span class="hljs-type">DogService</span>

  <span class="hljs-keyword">init</span>(dogService: <span class="hljs-type">DogService</span>) {
    <span class="hljs-keyword">self</span>.dogService = dogService
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await dogService.loadDogs()
    } <span class="hljs-keyword">catch</span> { 
      <span class="hljs-keyword">throw</span> error
    }
  }
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: ("[https://any-url.com]") is not equal to ("[https://dog.ceo/api/breeds/image/random/3]")</em></p>
<p>Let’s make it pass using the right URL</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogService</span> </span>{
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">let</span> loadDogsRequest = <span class="hljs-type">URLRequest</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://dog.ceo/api/breeds/image/random/3"</span>)!)
  ...
}
</code></pre>
<hr />
<p>The setup to init the SUT is a bit verbose
Let's create an helper function to avoid to always repeat</p>
<pre><code class="lang-swift">  <span class="hljs-comment">// MARK: - Helpers</span>

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeSUT</span><span class="hljs-params">(
    loadDogsResult: Result&lt;<span class="hljs-params">(Data, URLResponse)</span></span></span>, <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>&gt; = .failure(.connectivity)) <span class="hljs-comment">// 1</span>
  -&gt; (sut: <span class="hljs-type">DogsViewModel</span>, urlSessionSpy: <span class="hljs-type">URLSessionAsyncAwaitSpy</span>) {
    <span class="hljs-keyword">let</span> urlSessionSpy = <span class="hljs-type">URLSessionAsyncAwaitSpy</span>(result: loadDogsResult)
    <span class="hljs-keyword">let</span> networkService = <span class="hljs-type">NetworkService</span>(session: urlSessionSpy)
    <span class="hljs-keyword">let</span> dogService = <span class="hljs-type">DogService</span>(networkService: networkService)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">DogsViewModel</span>(dogService: dogService)
    <span class="hljs-keyword">return</span> (sut, urlSessionSpy)
  }
</code></pre>
<ol>
<li>Inject the mock result of loading dogs on SUT creation. Add a default value to hide details for tests where the result in not relevant.</li>
</ol>
<p>Refactor the 2 tests with the makeSUT() function</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_init_statusIdle</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT()

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, .idle)
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadDogs_performARequestWithDogsURLRequest</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> dogsURLRequest = <span class="hljs-type">URLRequest</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://dog.ceo/api/breeds/image/random/3"</span>)!)
    <span class="hljs-keyword">let</span> (sut, urlSessionSpy) = makeSUT()

    <span class="hljs-keyword">try</span>? await sut.loadDogs()

    <span class="hljs-type">XCTAssertEqual</span>(urlSessionSpy.requests, [dogsURLRequest])
  }
</code></pre>
<p>Run tests<br />They are passing  </p>
<hr />
<p>Continue with this requirement for  </p>
<pre>
 ========= LOAD DOGS
   [ ] Load dogs update status to loading
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadDogs_statusLoading</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(.connectivity))

    <span class="hljs-keyword">try</span>? await sut.loadDogs()

    <span class="hljs-type">XCTAssertEqual</span>(sut.messages, [.status(.loading)]) <span class="hljs-comment">// 1</span>
  }
</code></pre>
<ol>
<li>Needs to create the messages property that will capture all status values update.  </li>
</ol>
<p>Fix the error for Xcode to compile<br />First create a <code>DogsViewModelSpy</code><br />It captures the status updates  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModelSpy</span>: <span class="hljs-title">DogsViewModel</span> </span>{
    <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Message</span>: <span class="hljs-title">Equatable</span> </span>{
      <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> == <span class="hljs-params">(lhs: Message, rhs: Message)</span></span> -&gt; <span class="hljs-type">Bool</span> {
        <span class="hljs-keyword">switch</span> (lhs, rhs) {
        <span class="hljs-keyword">case</span> (status(<span class="hljs-keyword">let</span> status1), status(<span class="hljs-keyword">let</span> status2)):
          <span class="hljs-keyword">return</span> status1 == status2 ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>
        }
      }

      <span class="hljs-keyword">case</span> status(<span class="hljs-type">DogsViewModel</span>.<span class="hljs-type">Status</span>)
    }

    <span class="hljs-keyword">var</span> messages = [<span class="hljs-type">Message</span>]()

    <span class="hljs-keyword">override</span> <span class="hljs-keyword">var</span> status: <span class="hljs-type">DogsViewModel</span>.<span class="hljs-type">Status</span> {
      <span class="hljs-keyword">didSet</span> { messages.append(.status(status)) }
    }
}
</code></pre>
<p>Update the <code>DogsViewModel</code> with the loading status<br />Make it <code>Equatable</code> to able to compare  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span>: <span class="hljs-title">Equatable</span> </span>{ <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> == <span class="hljs-params">(lhs: DogsViewModel.Status, rhs: DogsViewModel.Status)</span></span> -&gt; <span class="hljs-type">Bool</span> {
      <span class="hljs-keyword">switch</span> (lhs, rhs) {
      <span class="hljs-keyword">case</span> (.idle, .idle), (.loading, .loading):
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
      <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
      }
    }

    <span class="hljs-keyword">case</span> idle
    <span class="hljs-keyword">case</span> loading <span class="hljs-comment">// 2</span>
  }
  ...
}
</code></pre>
<ol>
<li>Make the enum <code>Status</code> conform to <code>Equatable</code>, to be able to compare them</li>
<li>Add the <code>loading</code> case</li>
</ol>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: ("[]") is not equal to ("[AsyncAwaitTests.AsyncAwaitTests.(unknown context at $1038858a0).DogsViewModelSpy.Message.status(AsyncAwait.DogsViewModel.Status.loading)]")</em></p>
<p>Let’s make it pass on updating the status to loading  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    status = .loading  👈
  ...
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done  </p>
<pre>
 ========= LOAD DOGS
 [✅] Load dogs update status to loading
</pre>

<hr />
<p>Continue with this requirement for error on request API</p>
<pre>
 ========= LOAD DOGS
   [ ] If Load dogs failed delivers .connectivity error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliversConnectivityErrorOnNetworkError</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> connectivityError = <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>.connectivity
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(connectivityError))

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await sut.loadDogs()
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expected to failed"</span>) <span class="hljs-comment">// 1</span>
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-type">XCTAssertEqual</span>(error <span class="hljs-keyword">as</span>? <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>, connectivityError)
    }
  }
</code></pre>
<ol>
<li>We expect a failure here. If request succeed the test must failed.  </li>
</ol>
<p>Run tests<br />They are passing<br />With <code>async</code> function you always need to complete<br />The <code>await</code> keyword will block us until success or throws error<br />And to be able to write previous test<br />I always complete SUT with a .connectivity error  </p>
<p>Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
 [✅] If Load dogs failed delivers .connectivity error
</pre>

<hr />
<p>Continue with this requirement for display an error message on network error</p>
<pre>
 ========= LOAD DOGS
   [ ] Display an error message (text) on .connectivity error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_onRequestError_displayMessageInfo</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(.connectivity))

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await sut.loadDogs()
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expected to failed"</span>)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-comment">// 1</span>
      <span class="hljs-type">XCTAssertEqual</span>(sut.error, .loadDogs, <span class="hljs-string">"Expect error update or the alert will not be displayed"</span>)
      <span class="hljs-comment">// 2</span>
      <span class="hljs-type">XCTAssertEqual</span>(sut.alertTitle(), <span class="hljs-string">"Error loading dogs"</span>, <span class="hljs-string">"Expected a title or the alert will be displayed without it"</span>) 
    }
  }
</code></pre>
<ol>
<li>Need to create the <code>error</code> property that is responsible to display an alert on screen</li>
<li>Need to create the function <code>alertTitle()</code> that return the title of the alert for <code>.connectivity</code> error</li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Error</span>: <span class="hljs-title">String</span>, <span class="hljs-title">Swift</span>.<span class="hljs-title">Error</span>, <span class="hljs-title">Identifiable</span> </span>{
    <span class="hljs-keyword">case</span> loadDogs

    <span class="hljs-keyword">var</span> id: <span class="hljs-type">String</span> {
      <span class="hljs-keyword">self</span>.rawValue
    }
  }
  ...
  <span class="hljs-keyword">var</span> error: <span class="hljs-type">Error?</span>
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    status = .loading

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await dogService.loadDogs()
    } <span class="hljs-keyword">catch</span> <span class="hljs-keyword">let</span> error <span class="hljs-keyword">as</span> <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span> {
      <span class="hljs-keyword">switch</span> error {
      <span class="hljs-keyword">case</span> .connectivity:
        <span class="hljs-keyword">self</span>.error = .loadDogs 👈
      }
      <span class="hljs-keyword">throw</span> error
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">alertTitle</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">switch</span> error {
    <span class="hljs-keyword">case</span> .loadDogs:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Error loading dogs"</span>
    <span class="hljs-keyword">case</span> .<span class="hljs-keyword">none</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>
    }
  }
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
 [✅] Display an error message (text) on .connectivity error
</pre>

<hr />
<p>Continue with this requirement for retry on load error  </p>
<pre>
 ========= LOAD DOGS
   [ ] User can retry to load (button) on .connectivity error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_retryLoadDogs_loadDogs</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(.connectivity))

    await sut.retryLoadDogs() <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertEqual</span>(sut.messages, [.status(.loading)])
  }
</code></pre>
<ol>
<li>Need to create the <code>retryLoadDogs()</code> function </li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">retryLoadDogs</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">try</span>? await loadDogs()
  }
  ...
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done  </p>
<pre>
 ========= LOAD DOGS
 [✅] User can retry to load (button) on .connectivity error
</pre>

<hr />
<p>Continue with this requirement for succeeded to load but return an empty JSON</p>
<pre>
 ========= LOAD DOGS
   [ ] Load dogs succeed with 200 response
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadHereos_deliversSuccess200HTTPResponseWithEmptyDogsJSON</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> emptyDogsJSON = <span class="hljs-type">Data</span>(<span class="hljs-string">"{\"message\": []}"</span>.utf8)
    <span class="hljs-keyword">let</span> expectedEmptyDogs = [<span class="hljs-type">DogUI</span>]() <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .success((emptyDogsJSON, httpResponse(with: <span class="hljs-number">200</span>)))) <span class="hljs-comment">// 2</span>

    <span class="hljs-keyword">try</span>? await sut.loadDogs()
    waitForUICompletion() <span class="hljs-comment">// 3</span>

    <span class="hljs-type">XCTAssertEqual</span>(sut.messages, [.status(.loading), .status(.loaded(dogs: expectedEmptyDogs))]) <span class="hljs-comment">// 4</span>
  }
</code></pre>
<ol>
<li>Create the <code>DogUI</code> model that represent the dog requirement to display the UI.  </li>
<li>Create the <code>httpResponse(with:)</code> helper function that simulate an http response.  </li>
<li>Create the <code>waitForUICompletion()</code> helper function that wait until the async update of UI completes.  </li>
<li>Add the <code>.loaded(dogs:)</code> status case.  </li>
</ol>
<p>First the <code>DogUI</code> model</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogUI</span> </span>{

}
</code></pre>
<p>Second create the <code>httpResponse(with:)</code> and <code>waitForUICompletion()</code> helpers functions</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AsyncAwaitTests</span>: <span class="hljs-title">XCTestCase</span> </span>{
  ...
  <span class="hljs-comment">// MARK: - Helpers</span>
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">anyURL</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">URL</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://any-url.com"</span>)!
  }

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">httpResponse</span><span class="hljs-params">(with statusCode: Int)</span></span> -&gt; <span class="hljs-type">HTTPURLResponse</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-type">HTTPURLResponse</span>(url: anyURL(), statusCode: statusCode, httpVersion: <span class="hljs-literal">nil</span>, headerFields: <span class="hljs-literal">nil</span>)!
  }

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">waitForUICompletion</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> expectation = <span class="hljs-keyword">self</span>.expectation(description: <span class="hljs-string">"Expect that ui update on the main thread completes"</span>)
    <span class="hljs-type">DispatchQueue</span>.main.async {
        expectation.fulfill()
    }
    wait(<span class="hljs-keyword">for</span>: [expectation], timeout: <span class="hljs-number">1</span>)
  }
}
</code></pre>
<p>Fourth add the <code>.loaded(dogs:)</code> status case</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span>: <span class="hljs-title">Equatable</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> == <span class="hljs-params">(lhs: DogsViewModel.Status, rhs: DogsViewModel.Status)</span></span> -&gt; <span class="hljs-type">Bool</span> {
      <span class="hljs-keyword">switch</span> (lhs, rhs) {
      <span class="hljs-keyword">case</span> (.idle, .idle), (.loading, .loading):
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
      <span class="hljs-keyword">case</span> (.loaded(dogs: <span class="hljs-keyword">let</span> dogs1), .loaded(dogs: <span class="hljs-keyword">let</span> dogs2)):  👈
        <span class="hljs-keyword">return</span> dogs1 == dogs2 ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span> <span class="hljs-comment">// 1</span>
      <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
      }
    }

    <span class="hljs-keyword">case</span> idle
    <span class="hljs-keyword">case</span> loading
    <span class="hljs-keyword">case</span> loaded(dogs: [<span class="hljs-type">DogUI</span>])  👈
  }
  ...
}
</code></pre>
<ol>
<li>The DogUI needs to conform to <code>Equatable</code> to be able to compare<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogUI</span>: <span class="hljs-title">Equatable</span> </span>{
...
}
</code></pre>
</li>
</ol>
<p>Run the test and it fails<br />The status .loaded has never been called<br /><em>XCTAssertEqual failed: ("[AsyncAwaitTests.AsyncAwaitTests.(unknown context at $10c899490).DogsViewModelSpy.Message.status(AsyncAwait.DogsViewModel.Status.loading)]") is not equal to ("[AsyncAwaitTests.AsyncAwaitTests.(unknown context at $10c899490).DogsViewModelSpy.Message.status(AsyncAwait.DogsViewModel.Status.loading), AsyncAwaitTests.AsyncAwaitTests.(unknown context at $10c899490).DogsViewModelSpy.Message.status(AsyncAwait.DogsViewModel.Status.loaded(dogs: []))]")</em></p>
<p>Let’s make it pass<br />Start by update the status with the loaded dogs  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    ...    
    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">let</span> dogs = <span class="hljs-keyword">try</span> await dogService.loadDogs()
      <span class="hljs-type">DispatchQueue</span>.main.async {
        <span class="hljs-keyword">self</span>.status = .loaded(dogs: dogs)
      }
    } <span class="hljs-keyword">catch</span> <span class="hljs-keyword">let</span> error <span class="hljs-keyword">as</span> <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span> {
      ...
    }
  }
  ...
}
</code></pre>
<p>After handle the response<br />Check the status code 200<br />Parse the object using <code>Decodable</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogService</span> </span>{
    ...
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; [<span class="hljs-type">DogUI</span>] {
    <span class="hljs-keyword">do</span> {
      <span class="hljs-number">_</span> = <span class="hljs-keyword">try</span> await networkService.perform(request: loadDogsRequest)
      <span class="hljs-keyword">let</span> (data, response) = <span class="hljs-keyword">try</span> await networkService.perform(request: loadDogsRequest)
      <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> httpResponse = response <span class="hljs-keyword">as</span>? <span class="hljs-type">HTTPURLResponse</span>, httpResponse.statusCode == <span class="hljs-number">200</span> {
        <span class="hljs-keyword">let</span> decoder = <span class="hljs-type">JSONDecoder</span>()
        <span class="hljs-keyword">do</span> {
          <span class="hljs-keyword">let</span> dogsApi = <span class="hljs-keyword">try</span> decoder.decode(<span class="hljs-type">DogsApi</span>.<span class="hljs-keyword">self</span>, from: data) <span class="hljs-comment">// 1</span>
          <span class="hljs-keyword">let</span> dogs = dogsApi.message.<span class="hljs-built_in">map</span>{ <span class="hljs-type">DogUI</span>(url: <span class="hljs-type">URL</span>(string: $<span class="hljs-number">0</span>)) } <span class="hljs-comment">// 2</span>
          <span class="hljs-keyword">return</span> dogs
        }
        <span class="hljs-keyword">catch</span> {

        }
      }
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-keyword">throw</span> error
    }

    <span class="hljs-keyword">return</span> []
  }
}
</code></pre>
<ol>
<li>Need to create the <code>DogApi</code> model</li>
<li>Add the <code>url</code> property to the <code>DogUI</code> model</li>
</ol>
<p>First create the <code>DogApi</code> model</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogsApi</span>: <span class="hljs-title">Decodable</span> </span>{
  <span class="hljs-keyword">let</span> message: [<span class="hljs-type">String</span>]
}
</code></pre>
<p>Second add the <code>url</code> property to the <code>DogUI</code> model</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogUI</span>: <span class="hljs-title">Equatable</span> </span>{
  <span class="hljs-keyword">let</span> url: <span class="hljs-type">URL?</span>
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done  </p>
<pre>
 ========= LOAD DOGS
 [✅] Load dogs succeed with 200 response
</pre>

<hr />
<p>Continue with this requirement for decodable parsing succeeded</p>
<pre>
 ========= LOAD DOGS
   [ ] Parsing succeed delivers dogs
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadHereos_deliversDogsOnSuccess200HTTPResponse</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> validDogsJSON = <span class="hljs-type">Data</span>(<span class="hljs-string">"{\"message\": [\"https://images.dog.ceo/breeds/husky/n02110185_10116.jpg\"]}"</span>.utf8)
    <span class="hljs-keyword">let</span> expectedDogs = <span class="hljs-type">DogUI</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://images.dog.ceo/breeds/husky/n02110185_10116.jpg"</span>)!)
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .success((validDogsJSON, httpResponse(with: <span class="hljs-number">200</span>))))

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await sut.loadDogs()
      waitForUICompletion()

      <span class="hljs-type">XCTAssertEqual</span>(sut.status, .loaded(dogs: [expectedDogs]))
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expected to succeeded, got error \(error) instead"</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done  </p>
<pre>
 ========= LOAD DOGS
 [✅] Load dogs succeed with 200 response
</pre>

<hr />
<p>Continue with this requirement for dogs names extract from url</p>
<pre>
 ========= LOAD DOGS
   [ ] Extract dogs names from returned url
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_dogsName_extractDogsNamesFromPicturesURL</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> pictureURL1 = <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://images.dog.ceo/breeds/setter-english/n02100735_10038.jpg"</span>)!
    <span class="hljs-keyword">let</span> pictureURL2 = <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://images.dog.ceo/breeds/komondor/n02105505_1657.jpg"</span>)!
    <span class="hljs-keyword">let</span> dog1 = <span class="hljs-type">DogUI</span>(url: pictureURL1)
    <span class="hljs-keyword">let</span> dog2 = <span class="hljs-type">DogUI</span>(url: pictureURL2)
    <span class="hljs-keyword">let</span> expectDogsName1 = <span class="hljs-string">"Setter English"</span>
    <span class="hljs-keyword">let</span> expectDogsName2 = <span class="hljs-string">"Komondor"</span>

    <span class="hljs-type">XCTAssertEqual</span>(dog1.name, expectDogsName1) <span class="hljs-comment">// 1</span>
    <span class="hljs-type">XCTAssertEqual</span>(dog2.name, expectDogsName2) <span class="hljs-comment">// 1</span>
  }
</code></pre>
<ol>
<li>Needs to create the <code>name</code> property</li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogUI</span>: <span class="hljs-title">Equatable</span> </span>{
  <span class="hljs-keyword">let</span> url: <span class="hljs-type">URL?</span>
  👇
  <span class="hljs-keyword">var</span> name: <span class="hljs-type">String</span> { 
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> urlString = url?.absoluteString {
      <span class="hljs-keyword">return</span> urlString
        .components(separatedBy: <span class="hljs-string">"/"</span>)[<span class="hljs-number">4</span>]
        .replacingOccurrences(of: <span class="hljs-string">"-"</span>, with: <span class="hljs-string">" "</span>)
        .capitalized
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Unknown"</span>
    }
  }
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
 [✅] Extract dogs names from returned url
</pre>

<hr />
<p>Continue with this requirement for <code>Decodable</code> failure</p>
<pre>
 ========= LOAD DOGS
   [ ] Parsing failed delivers .invalidData error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadHereos_deliversErrorOn200HTTPResponseWithInvalidData</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> expectedError = <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>.invalidData <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> invalidDogsJSON = <span class="hljs-type">Data</span>(<span class="hljs-string">""</span>.utf8)
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .success((invalidDogsJSON, httpResponse(with: <span class="hljs-number">200</span>))))

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await sut.loadDogs()
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expected to failed the JSON cannot be decoded"</span>)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-type">XCTAssertEqual</span>(error <span class="hljs-keyword">as</span>? <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>, expectedError)
    }
  }
</code></pre>
<ol>
<li>Needs to create the .invalidData error case</li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NetworkService</span> </span>{
  ...
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Error</span>: <span class="hljs-title">Swift</span>.<span class="hljs-title">Error</span> </span>{
    <span class="hljs-keyword">case</span> connectivity
    <span class="hljs-keyword">case</span> invalidData 👈
  }
  ...
}
</code></pre>
<p>Run the test and it fails<br />Handle the new <code>.invalidData</code> case</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
  ...
      <span class="hljs-keyword">switch</span> error {
      <span class="hljs-keyword">case</span> .connectivity:
        <span class="hljs-keyword">self</span>.error = .loadDogs
      <span class="hljs-keyword">case</span> .invalidData:  👈
        <span class="hljs-keyword">break</span>
      }
  ...
  }
}
</code></pre>
<p>Send <code>.invalidData</code> error on decode failure</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogService</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> -&gt; [<span class="hljs-type">DogUI</span>] {
    ...
          <span class="hljs-keyword">do</span> {
          <span class="hljs-keyword">let</span> dogsApi = <span class="hljs-keyword">try</span> decoder.decode(<span class="hljs-type">DogsApi</span>.<span class="hljs-keyword">self</span>, from: data)
          <span class="hljs-keyword">let</span> dogs = dogsApi.message.<span class="hljs-built_in">map</span>{ <span class="hljs-type">DogUI</span>(url: <span class="hljs-type">URL</span>(string: $<span class="hljs-number">0</span>)) }
          <span class="hljs-keyword">return</span> dogs
        } <span class="hljs-keyword">catch</span> {
          <span class="hljs-keyword">throw</span> <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>.invalidData 👈
        }
    ...
  }
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done  </p>
<pre>
 ========= LOAD DOGS
 [✅] Parsing failed delivers .invalidData error
</pre>

<hr />
<p>Continue with this requirement for message error on .invalidData error</p>
<pre>
 ========= LOAD DOGS
   [ ] Display an error message (text) on .invalidData error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_displayErrorMessageoOnInvalidDataError</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> expectedErrorText = <span class="hljs-string">"Error parsing dogs"</span>
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(.invalidData))

    <span class="hljs-type">XCTAssertEqual</span>(sut.alertTitle(), <span class="hljs-string">""</span>, <span class="hljs-string">"Expected to get an empty string as default value"</span>)

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">try</span> await sut.loadDogs()
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expected to failed"</span>)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-type">XCTAssertEqual</span>(sut.error, .parsingDogs) <span class="hljs-comment">// 1</span>
      <span class="hljs-type">XCTAssertEqual</span>(sut.alertTitle(), expectedErrorText)
    }
  }
</code></pre>
<ol>
<li>Needs to create the .parsingDogs error in the view model</li>
</ol>
<p>Fix the error for Xcode to compile<br />Add the .parsingDogs error<br />The function <code>loadDogs</code> must handle this new case<br />Update the <code>alertTitle()</code> function with this new case  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DogsViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Error</span>: <span class="hljs-title">String</span>, <span class="hljs-title">Swift</span>.<span class="hljs-title">Error</span>, <span class="hljs-title">Identifiable</span> </span>{
    <span class="hljs-keyword">case</span> loadDogs
    <span class="hljs-keyword">case</span> parsingDogs 👈
    ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">loadDogs</span><span class="hljs-params">()</span></span> async <span class="hljs-keyword">throws</span> {
      <span class="hljs-keyword">switch</span> error {
      <span class="hljs-keyword">case</span> .connectivity:
        <span class="hljs-keyword">self</span>.error = .loadDogs
      <span class="hljs-keyword">case</span> .invalidData:
        <span class="hljs-keyword">self</span>.error = .parsingDogs 👈
      }
   }
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">alertTitle</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">switch</span> error {
    <span class="hljs-keyword">case</span> .loadDogs:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Error loading dogs"</span>
    <span class="hljs-keyword">case</span> .parsingDogs: 👈
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Error parsing dogs"</span> 
    <span class="hljs-keyword">case</span> .<span class="hljs-keyword">none</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>
    }
  }
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
 [✅] Display an error message (text) on .invalidData error
</pre>

<hr />
<p>Continue with this requirement for retry on <code>.invalidData</code> error</p>
<pre>
 ========= LOAD DOGS
   [ ] User can retry to load (button) on .invalidData error
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_loadHereos_onParsingError_userCanRetryToLoad</span><span class="hljs-params">()</span></span> async {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT(loadDogsResult: .failure(.invalidData))

    await sut.retryLoadDogs()

    <span class="hljs-type">XCTAssertEqual</span>(sut.messages, [.status(.loading)])
  }
</code></pre>
<p>Run tests<br />They are passing<br />The <code>retryLoadDogs()</code> function already exist 
Can mark this requirement as done.  </p>
<pre>
 ========= LOAD DOGS
 [✅] User can retry to load (button) on .invalidData error
</pre>

<hr />
<p>Now let's create the view that implement the view model</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogsView</span>: <span class="hljs-title">View</span> </span>{
  @<span class="hljs-type">ObservedObject</span> <span class="hljs-keyword">var</span> viewModel: <span class="hljs-type">DogsViewModel</span>

  <span class="hljs-keyword">var</span> body: some <span class="hljs-type">View</span> {
    <span class="hljs-type">NavigationView</span> {
      <span class="hljs-type">ZStack</span> {
        <span class="hljs-keyword">switch</span> viewModel.status {
        <span class="hljs-keyword">case</span> .idle:
          <span class="hljs-type">EmptyView</span>()
        <span class="hljs-keyword">case</span> .loading:
          <span class="hljs-type">ProgressView</span>()
        <span class="hljs-keyword">case</span> .loaded(dogs: <span class="hljs-keyword">let</span> dogs):
          <span class="hljs-type">ZStack</span> {
            <span class="hljs-type">Color</span>(<span class="hljs-type">UIColor</span>.secondarySystemBackground)
              .edgesIgnoringSafeArea(.all)
            <span class="hljs-type">ScrollView</span> {
              <span class="hljs-type">LazyVStack</span>(spacing: <span class="hljs-number">34</span>) {
                <span class="hljs-type">ForEach</span>(dogs, id: \.url) { dog <span class="hljs-keyword">in</span>
                  <span class="hljs-type">VStack</span>(spacing: <span class="hljs-number">0</span>) {
                    <span class="hljs-type">AsyncImage</span>(url: dog.url) { phase <span class="hljs-keyword">in</span>
                      <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> image = phase.image {
                        image <span class="hljs-comment">// Displays the loaded image.</span>
                          .resizable()
                          .scaledToFill()
                          .frame(width: <span class="hljs-type">UIScreen</span>.main.bounds.width - <span class="hljs-number">32</span>, height: <span class="hljs-type">UIScreen</span>.main.bounds.width, alignment: .center)
                          .clipped()
                      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> phase.error != <span class="hljs-literal">nil</span> {
                        <span class="hljs-type">Color</span>.red <span class="hljs-comment">// Indicates an error.</span>
                          .frame(width: <span class="hljs-type">UIScreen</span>.main.bounds.width - <span class="hljs-number">32</span>, height: <span class="hljs-type">UIScreen</span>.main.bounds.width, alignment: .center)
                      } <span class="hljs-keyword">else</span> {
                        <span class="hljs-type">ZStack</span> { <span class="hljs-comment">// Acts as a placeholder.</span>
                          <span class="hljs-type">Color</span>(<span class="hljs-type">UIColor</span>.tertiarySystemBackground)
                            .frame(width: <span class="hljs-type">UIScreen</span>.main.bounds.width - <span class="hljs-number">32</span>, height: <span class="hljs-type">UIScreen</span>.main.bounds.width, alignment: .center)
                          <span class="hljs-type">ProgressView</span>()
                            .scaleEffect(<span class="hljs-number">4</span>)
                            .progressViewStyle(<span class="hljs-type">CircularProgressViewStyle</span>(tint: <span class="hljs-type">SwiftUI</span>.<span class="hljs-type">Color</span>(<span class="hljs-type">UIColor</span>.label).opacity(<span class="hljs-number">0.5</span>)))
                        }
                      }
                    }
                    <span class="hljs-type">Text</span>(dog.name)
                      .font(.title)
                      .foregroundColor(<span class="hljs-type">SwiftUI</span>.<span class="hljs-type">Color</span>.primary)
                      .padding()
                  }
                  .background(<span class="hljs-type">SwiftUI</span>.<span class="hljs-type">Color</span>(<span class="hljs-type">UIColor</span>.tertiarySystemBackground))
                  .cornerRadius(<span class="hljs-number">20</span>)
                  .shadow(color: <span class="hljs-type">Color</span>.black.opacity(<span class="hljs-number">0.25</span>), radius: <span class="hljs-number">20</span>, x: <span class="hljs-number">0</span>, y: <span class="hljs-number">3</span>)
                }
              }
            }
            .padding(.top, <span class="hljs-number">32</span>)
          }
        }
      }
      .navigationTitle(<span class="hljs-string">"Dogs"</span>)
    }
    .task {
      <span class="hljs-keyword">try</span>? await viewModel.loadDogs()
    }
    .alert(item: $viewModel.error) { <span class="hljs-number">_</span> <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">return</span> <span class="hljs-type">Alert</span>(
        title: <span class="hljs-type">Text</span>(viewModel.alertTitle()),
        message: <span class="hljs-literal">nil</span>,
        dismissButton: .<span class="hljs-keyword">default</span>(<span class="hljs-type">Text</span>(<span class="hljs-string">"RETRY"</span>)) {
          <span class="hljs-type">Task</span> {
            await viewModel.retryLoadDogs()
          }
        })
    }
  }
}
</code></pre>
<p>To preview the result let's create a fake view model<br />It will first simulate a .connectivity network error<br />Second an .invalidData parsing error<br />Third a success response with 3 dogs  </p>
<p>Start creating setting the preview</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">DogsView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-type">DogsView</span>(viewModel: fakeViewModel()) <span class="hljs-comment">// 1</span>
  }
}
</code></pre>
<ol>
<li>Needs to create this <code>fakeViewModel</code> that doesn't exist</li>
</ol>
<p>Create the <code>fakeViewModel</code> </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fakeViewModel</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">DogsViewModel</span> {
    <span class="hljs-keyword">let</span> urlSessionSpy = <span class="hljs-type">URLSessionAsyncAwaitSpy</span>( <span class="hljs-comment">// 1</span>
      results:
        [
          .failure(.connectivity),
          .failure(.invalidData),
          .success((validData(), validResponse())) <span class="hljs-comment">// 2</span>
        ]
    )
    <span class="hljs-keyword">let</span> networkService = <span class="hljs-type">NetworkService</span>(session: urlSessionSpy)
    <span class="hljs-keyword">let</span> service = <span class="hljs-type">DogService</span>(networkService: networkService)
    <span class="hljs-keyword">return</span> <span class="hljs-type">DogsViewModel</span>(dogService: service)
  }
</code></pre>
<ol>
<li>Need to create the <code>URLSessionAsyncAwaitSpy</code> that will handle all fake results API</li>
<li>Need to create <code>validData()</code> and <code>validResponse()</code> that will simulate the fake valid response</li>
</ol>
<p>First create the <code>URLSessionAsyncAwaitSpy</code></p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">URLSessionAsyncAwaitSpy</span>: <span class="hljs-title">AsyncAwait</span> </span>{
    <span class="hljs-keyword">var</span> results: [<span class="hljs-type">Result</span>&lt;(<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>), <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>&gt;]

    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">init</span>(results: [<span class="hljs-type">Result</span>&lt;(<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>), <span class="hljs-type">NetworkService</span>.<span class="hljs-type">Error</span>&gt;]) {
      <span class="hljs-keyword">self</span>.results = results
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">data</span><span class="hljs-params">(request: URLRequest)</span></span> async <span class="hljs-keyword">throws</span> -&gt; (<span class="hljs-type">Data</span>, <span class="hljs-type">URLResponse</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> results.removeFirst().<span class="hljs-keyword">get</span>() <span class="hljs-comment">// 1</span>
    }
  }
</code></pre>
<ol>
<li>Use the <code>removeFirst()</code> function to return the result and will be ready for the next one</li>
</ol>
<p>Second create <code>validData()</code> and <code>validResponse()</code></p>
<pre><code class="lang-swift">  <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">validData</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Data</span> {
    <span class="hljs-keyword">let</span> dogsJSON =
    [
      <span class="hljs-string">"message"</span>:
        [
          <span class="hljs-string">"https://images.dog.ceo/breeds/setter-english/n02100735_10038.jpg"</span>,
          <span class="hljs-string">"https://images.dog.ceo/breeds/retriever-golden/n02099601_6331.jpg"</span>,
          <span class="hljs-string">"https://images.dog.ceo/breeds/komondor/n02105505_1657.jpg"</span>
        ]
    ]

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> <span class="hljs-type">JSONSerialization</span>.data(withJSONObject: dogsJSON)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-built_in">assertionFailure</span>(<span class="hljs-string">"Expected to get a valid JSON, got error \(error) instead"</span>)
      <span class="hljs-keyword">return</span> <span class="hljs-type">Data</span>()
    }
  }

  <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">validResponse</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">HTTPURLResponse</span> {
    <span class="hljs-type">HTTPURLResponse</span>(url: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"https://any-url.com"</span>)!, statusCode: <span class="hljs-number">200</span>, httpVersion: <span class="hljs-literal">nil</span>, headerFields: <span class="hljs-literal">nil</span>)!
  }
</code></pre>
<p>Run the preview<br />First we failed as expected with a .connectivity error<br />With the expected message create when TDD the view model
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1665606474527/TgloNRdnG.png" alt="image.png" /></p>
<p>Tap the RETRY button the and the .invalidData error appear
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1665606562664/YcC1Bcppj.png" alt="image.png" /></p>
<p>Tap the RETRY button and the success with valid data will be displayed
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1665606632333/JYAS3AhXf.png" alt="image.png" /></p>
<hr />
<p>I hope you enjoy this TDD journey with async/await<br />async/await can be tested using stub (inject result)<br />Because it needs how it will complete before method execution<br />Or you will always be block by <code>await</code><br />If never completes with success or error  </p>
<p>That's it !!  </p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - Extract navigation logic from SwiftUI views for testability]]></title><description><![CDATA[SwiftUI is very powerful tool, for UI creation and animationBut I really don't like the navigation logicThat is couples with SwiftUI views with…]]></description><link>https://swiftuicentral.com/swiftui-extract-navigation-logic-from-swiftui-views-for-testability</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-extract-navigation-logic-from-swiftui-views-for-testability</guid><category><![CDATA[SwiftUI]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[Swift]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Tue, 21 Jun 2022 11:33:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/NXt5PrOb_7U/upload/v1655811332471/sXFpIhg3n.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-to-test-your-navigation-logic-in-swiftui">Problem: How to test your navigation logic in SwiftUI ?</h2>
<h3 id="heading-solution-extract-navigation-logic-in-a-separate-service-that-handles-it-using-uikit">Solution: Extract navigation logic in a separate Service that handles it using UIKit</h3>
<p>SwiftUI is very powerful tool, for UI creation and animation<br />But I really don't like the navigation logic<br />That is couples with SwiftUI views with <code>NavigationLink</code><br />Make it difficult to test<br />The idea here is to extract the navigation logic in a separate service<br />So SwiftUI views only have to use it<br />And doesn't know anything about navigation logic</p>
<p>I draw a diagram of the navigation logic<br />To better understand what we are trying to achieve<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655207076367/7Yoz6xgR0.png" alt="image.png" class="image--center mx-auto" /></p>
<p>Here we handle the navigation logic with <code>UIKit</code><br />So the navigation bar will be a <code>UINavigationBarController</code><br />Everything related with navigation bar:<br />Title, back button, left button item<br />Will be created using <code>UIKit</code> api (<code>UIAlertController</code>, <code>UIBarButtonItem</code>, ...)<br />Only navigation bar visibility will be handle by the SwiftUI view<br />Using the modifier <code>.navigationBarHidden(true)</code><br />Because when try to handle visibiity from <code>UIKit</code><br />I encountered crashes</p>
<p>From this diagram<br />And the <code>UIKit</code> requirement<br />I have a better idea of what I'm trying to achieve<br />I'm able to write those specs:  </p>
<pre>
 ========= LOGIN
 [ ] On init user not login set login view as root with no animation
   [ ] User first login push to the onboarding view
     [ ] Validate onboarding set the infos view as root with no animation
 [ ] On init user login set infos view as root with no animation

 ========= INFOS
 [ ] Infos can push to info details view
 [ ] Infos nav bar have a title
 [ ] Infos nav bar have a right button for logout
   [ ] Infos nav bar right button action present an alert sheet
     [ ] Alert sheet have a title (no message)
     [ ] Alert sheet have a cancel action (user can dismiss)
     [ ] Alert sheet have a logout action
       [ ] Confirm logout set login as root with no animation
         [ ] Login user after a logout set infos view as root (no onboarding)

 ========= INFOS DETAILS
 [ ] Infos details can push to new info view
 [ ] Infos details nav bar have a title
 [ ] Infos details nav bar have a back button (user can pop back)
 [ ] Infos details nav bar have a right button for create new info

 ========= NEW INFOS
 [ ] New info nav bar have a title
 [ ] New info nav bar have a back button (user can pop back)
 [ ] Create new info pop to the root view (infos view)
</pre>

<hr />
<p>Let's start with the first requirement for login  </p>
<pre>
 ========= LOGIN
 [ ] On init user not login set login view as root with no animation
</pre>

<p>Start writing the test   </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_init_userIsNotLogin_setLoginViewAsRootWithNoAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> userIsNotLogin = <span class="hljs-literal">false</span>
    <span class="hljs-keyword">let</span> navigationSpy = <span class="hljs-type">UINavigationControllerSpy</span>() <span class="hljs-comment">// 1</span>

    <span class="hljs-number">_</span> = <span class="hljs-type">NavigationService</span>(navigationController: navigationSpy, <span class="hljs-comment">// 2</span>
                          isLogin: userIsNotLogin)

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers.first <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">LoginView</span>&gt;, <span class="hljs-string">"Expect login view as root view controller"</span>)
    <span class="hljs-type">XCTAssertFalse</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect no animation when displaying the login view on init"</span>)
  }
</code></pre>
<p>The compiler is guiding us   </p>
<ol>
<li>He cannot find <code>UINavigationControllerSpy</code> in scope we need to create it  </li>
<li>He cannot find <code>NavigationService</code> in scope we need to create it  </li>
</ol>
<p>Create the <code>UINavigationControllerSpy</code> first<br />This is a spy because it just capture values  </p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UINavigationControllerSpy</span>: <span class="hljs-title">UINavigationController</span> </span>{
    <span class="hljs-keyword">var</span> controllers = [<span class="hljs-type">UIViewController</span>]()
    <span class="hljs-keyword">var</span> isAnimate = <span class="hljs-literal">false</span>

    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setViewControllers</span><span class="hljs-params">(<span class="hljs-number">_</span> viewControllers: [UIViewController], animated: Bool)</span></span> {
      <span class="hljs-keyword">self</span>.controllers = viewControllers
      <span class="hljs-keyword">self</span>.isAnimate = animated
    }
}
</code></pre>
<p>Now create the <code>NavigationService</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  <span class="hljs-keyword">let</span> isLogin: <span class="hljs-type">Bool</span>
  <span class="hljs-keyword">let</span> navigationController: <span class="hljs-type">UINavigationController</span>
  <span class="hljs-keyword">init</span>(navigationController: <span class="hljs-type">UINavigationController</span>, isLogin: <span class="hljs-type">Bool</span>) {
    <span class="hljs-keyword">self</span>.navigationController = navigationController
    <span class="hljs-keyword">self</span>.isLogin = isLogin

    <span class="hljs-keyword">if</span> !isLogin {
      setLoginViewAsRoot()
    }

  <span class="hljs-comment">// MARK: Helpers</span>
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setLoginViewAsRoot</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Do nothing want to see failed test first</span>
  }
}
</code></pre>
<p>Run the test and It fails<br /><em>XCTAssertTrue failed - Expect login view as root view controller</em></p>
<p>Let's make it pass<br />Setting the <code>Loginview</code> as root view controller  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setLoginViewAsRoot</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> loginViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">LoginView</span>()) <span class="hljs-comment">// 1</span>
    navigationController.setViewControllers([loginViewController], animated: <span class="hljs-literal">false</span>)
  }
</code></pre>
<ol>
<li>View controller is created from SwiftUI view using <code>UIHostingController</code>  </li>
</ol>
<p>Run the test it pass<br />Can checkmark this requirement as done  </p>
<pre>
 ========= LOGIN
 [✅] On init user not login set login view as root with no animation
</pre>

<hr />
<p>Continue with the second requirement for login  </p>
<pre>
 ========= LOGIN
   [ ] User first login push to the onboarding view
</pre>

<p>As usual writing the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_login_userIsFirstLogin_pushToOnboardingViewWithAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> userIsFirstLogin = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">let</span> userIsNotLogin = <span class="hljs-literal">false</span>
    <span class="hljs-keyword">let</span> navigationSpy = <span class="hljs-type">UINavigationControllerSpy</span>()

    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">NavigationService</span>(navigationController: navigationSpy,
                                isLogin: userIsNotLogin,
                                isFirstLogin: userIsFirstLogin) <span class="hljs-comment">// 1</span>

    sut.login() <span class="hljs-comment">// 2</span>

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers[<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">OnboardingView</span>&gt;, <span class="hljs-string">"Expect onboarding view visible"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when display onboarding view"</span>)
  }
</code></pre>
<ol>
<li>The compiler is guiding us with this error:<br /><em>Extra argument <code>isFirstLogin</code> in call</em> 
We need to add the <code>isFirstLogin</code> parameter.  </li>
<li>The <code>login()</code> function not exist we also need to create it  </li>
</ol>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-keyword">var</span> isFirstLogin: <span class="hljs-type">Bool</span>

  <span class="hljs-keyword">init</span>(navigationController: <span class="hljs-type">UINavigationController</span>, isLogin: <span class="hljs-type">Bool</span>, isFirstLogin: <span class="hljs-type">Bool</span>) {
    ...
    <span class="hljs-keyword">self</span>.isFirstLogin = isFirstLogin
    ...
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">if</span> isFirstLogin {
      displayOnboardingView()
    }
  }
  ...
  <span class="hljs-comment">// MARK: Helpers</span>
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">displayOnboardingView</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Do nothing want to see a test that failed first</span>
  }
}
</code></pre>
<p>Xcode can now compile<br />Run the test<br />It crash<br /><em>Fatal error: Index out of range</em>  </p>
<p>That is normal we need to update the <code>UINavigationControllerSpy</code>  </p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UINavigationControllerSpy</span>: <span class="hljs-title">UINavigationController</span> </span>{
  ...
  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">pushViewController</span><span class="hljs-params">(<span class="hljs-number">_</span> viewController: UIViewController, animated: Bool)</span></span> {
      <span class="hljs-keyword">self</span>.controllers.append(viewController)
      <span class="hljs-keyword">self</span>.isAnimate = animated
    }
  ...
}
</code></pre>
<p>And also the navigation that push the view  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">displayOnboardingView</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> onboardingViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">OnboardingView</span>())
    navigationController.pushViewController(onboardingViewController, animated: <span class="hljs-literal">true</span>)
  }
</code></pre>
<p>Run the test it pass<br />Can mark this spec as done  </p>
<pre>
 ========= LOGIN
 [✅] User first login push to the onboarding view
</pre>

<hr />
<p>To simply the test setup<br />Extract the sut creation to an helper method  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SwiftUINavigationTests</span>: <span class="hljs-title">XCTestCase</span> </span>{
  ...
  <span class="hljs-comment">// MARK: Helpers</span>

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeSUT</span><span class="hljs-params">(isLogin: Bool = <span class="hljs-literal">true</span>, isFirstLogin: Bool = <span class="hljs-literal">false</span>)</span></span> -&gt; (<span class="hljs-type">NavigationService</span>, <span class="hljs-type">UINavigationControllerSpy</span>) {
    <span class="hljs-keyword">let</span> navigationSpy = <span class="hljs-type">UINavigationControllerSpy</span>()
    <span class="hljs-keyword">let</span> navigationService = <span class="hljs-type">NavigationService</span>(
      navigationController: navigationSpy,
      isLogin: isLogin,
      isFirstLogin: isFirstLogin
    )
    <span class="hljs-keyword">return</span> (navigationService, navigationSpy)
  } 
}
</code></pre>
<p>You can use it like this for example</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_login_userIsFirstLogin_pushToOnboardingViewWithAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> userIsFirstLogin = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT(isLogin: <span class="hljs-literal">false</span>, isFirstLogin: userIsFirstLogin)

    sut.login()

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers[<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">OnboardingView</span>&gt;, <span class="hljs-string">"Expect onboarding view visible"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when display onboarding view"</span>)
  }
</code></pre>
<hr />
<p>Continue with this requirement for onboarding validation  </p>
<pre>
 ========= LOGIN
     [ ] Validate onboarding set the infos view as root with no animation
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_validateOnboarding_setInfosViewAsRootWithWithAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> userIsFirstLogin = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT(isLogin: <span class="hljs-literal">false</span>, isFirstLogin: userIsFirstLogin)

    sut.validateOnboarding() <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers.first <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">InfosView</span>&gt;, <span class="hljs-string">"Expect infos view visible"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when display infos view"</span>)
  }
</code></pre>
<ol>
<li>The <code>validateOnboarding()</code> function not exist we need to create it    </li>
</ol>
<p>Create the <code>validateOnboarding()</code> function</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">validateOnboarding</span><span class="hljs-params">()</span></span> {
    setInfosViewAsRoot(animated: <span class="hljs-literal">true</span>)
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    <span class="hljs-comment">// Do nothing want to see a failed test first</span>
  }
  ...
}
</code></pre>
<p>Run the test and it fails<br />Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    <span class="hljs-keyword">let</span> infosViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfosView</span>())
    navigationController.setViewControllers([infosViewController], animated: animated)
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOGIN
     [✅] Validate onboarding set the infos view as root with no animation
</pre>

<hr />
<p>Continue with this requirement for already login user</p>
<pre>
 ========= LOGIN
 [] On init user login set infos view as root with no animation
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_init_userIsLogin_setInfosViewAsRootWithNoAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> userIsLogin = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">let</span> (<span class="hljs-number">_</span>, navigationSpy) = makeSUT(isLogin: userIsLogin, isFirstLogin: <span class="hljs-literal">true</span>)

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers.first <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">InfosView</span>&gt;, <span class="hljs-string">"Expect infos view as root view controller"</span>)
    <span class="hljs-type">XCTAssertFalse</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect no animation when displaying the infos view on init"</span>)
  }
</code></pre>
<p>Run the test<br />He fails with error<br /><em>XCTAssertTrue failed - Expect infos view as root view controller</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-keyword">init</span>(navigationController: <span class="hljs-type">UINavigationController</span>, isLogin: <span class="hljs-type">Bool</span>, isFirstLogin: <span class="hljs-type">Bool</span>) {
    ...
    <span class="hljs-keyword">if</span> isLogin {
      setInfosViewAsRoot()
    } <span class="hljs-keyword">else</span> {
      setLoginViewAsRoot()
    }
  }
  ...
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOGIN
 [✅] On init user login set infos view as root with no animation
</pre>

<hr />
<p>Continue with this requirement for push to view details</p>
<pre>
 ========= INFOS
 [] Infos can push to info details view
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_displayInfoDetails_pushToInfoDetaisViewWithAnimation</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> info = <span class="hljs-type">Info</span>(title: <span class="hljs-string">"A title"</span>)
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.displayInfoDetails(<span class="hljs-keyword">for</span>: info) <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers[<span class="hljs-number">1</span>] <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">InfoDetailsView</span>&gt;, <span class="hljs-string">"Expect infos details view visible"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when display info details view"</span>)
  }
</code></pre>
<ol>
<li>The <code>displayInfoDetails(for:)</code> function not exist we need to create it  </li>
</ol>
<p>Create the <code>displayInfoDetails(for:)</code> for Xcode to compile    </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">displayInfoDetails</span><span class="hljs-params">(<span class="hljs-keyword">for</span> info: Info)</span></span> {
    <span class="hljs-comment">// Do nothing want to see a failed test first</span>
  }
</code></pre>
<p>Run the test and it fails with error<br /><em>Fatal error: Index out of range</em><br />Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">displayInfoDetails</span><span class="hljs-params">(<span class="hljs-keyword">for</span> info: Info)</span></span> {
    <span class="hljs-keyword">let</span> infoDetailsViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfoDetailsView</span>(info: info))
    navigationController.pushViewController(infoDetailsViewController, animated: <span class="hljs-literal">true</span>)
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Infos can push to info details view
</pre>

<hr />
<p>Continue with this requirement for infos nav bar title </p>
<pre>
 ========= INFOS
 [] Infos nav bar have a title
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_displayInfo_navBarWithTitle</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.setInfosViewAsRoot()

    <span class="hljs-keyword">let</span> controller = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.controllers.first)
    <span class="hljs-type">XCTAssertEqual</span>(controller.title, <span class="hljs-string">"Infos"</span>)
  }
</code></pre>
<p>Run the test and it fails with error<br /><em>XCTAssertEqual failed: ("nil") is not equal to ("Optional("Infos")")</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    <span class="hljs-keyword">let</span> infosViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfosView</span>())
    infosViewController.title = <span class="hljs-string">"Infos"</span>  👈  
    navigationController.setViewControllers([infosViewController], animated: animated)
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Infos nav bar have a title
</pre>

<hr />
<p>Continue with this requirement for infos logout button   </p>
<pre>
 ========= INFOS
   [ ] Infos nav bar have a right button for logout
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_displayInfo_navBarWithRightButtonLogout</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> rightBarItemImage = <span class="hljs-type">UIImage</span>(systemName: <span class="hljs-string">"arrowshape.turn.up.left.circle"</span>)
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.setInfosViewAsRoot()

    <span class="hljs-keyword">let</span> controller = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.controllers.first, <span class="hljs-string">"Expect info view controller"</span>)
    <span class="hljs-type">XCTAssertNotNil</span>(controller.navigationItem.rightBarButtonItem, <span class="hljs-string">"Expect a right bar button item"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(controller.navigationItem.rightBarButtonItem?.image, rightBarItemImage, <span class="hljs-string">"Expect identical image"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(controller.navigationItem.rightBarButtonItem?.style, .plain, <span class="hljs-string">"Expect identical style"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(controller.navigationItem.rightBarButtonItem?.tintColor, .red, <span class="hljs-string">"Expect identical tint color"</span>)
  }
</code></pre>
<p>Run the test and all assertions failed<br />Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    <span class="hljs-keyword">let</span> infosViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfosView</span>())
    infosViewController.title = <span class="hljs-string">"Infos"</span>
    <span class="hljs-keyword">let</span> logoutItem = <span class="hljs-type">UIBarButtonItem</span>(image: <span class="hljs-type">UIImage</span>(systemName: <span class="hljs-string">"arrowshape.turn.up.left.circle"</span>), style: .plain, target: <span class="hljs-keyword">self</span>, action: <span class="hljs-literal">nil</span>)  👈
    logoutItem.tintColor = .red 👈
    infosViewController.navigationItem.rightBarButtonItem = logoutItem 👈
    navigationController.setViewControllers([infosViewController], animated: animated)
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Infos nav bar have a right button for logout
</pre>

<hr />
<p>Continue with this requirement for logout button that present an alert sheet  </p>
<pre>
 ========= INFOS
   [ ] Infos nav bar right button action present an alert sheet
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_presentAlertSheetLogout_presentAnAlert</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    <span class="hljs-keyword">let</span> controller = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.controllers.first)
    <span class="hljs-type">XCTAssertEqual</span>(controller.navigationItem.rightBarButtonItem?.action?.description, <span class="hljs-string">"presentAlertSheetLogout"</span>, <span class="hljs-string">"Expect an action to present the logout view"</span>)

    sut.presentAlertSheetLogout() <span class="hljs-comment">// 1</span>

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>) <span class="hljs-comment">// 2</span>
    <span class="hljs-type">XCTAssertEqual</span>(navigationSpy.isAnimate, <span class="hljs-literal">true</span>, <span class="hljs-string">"Expect the alert presentation to be animated"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.preferredStyle, .actionSheet, <span class="hljs-string">"Expect the prefered style to be an .actionSheet"</span>)
  }
</code></pre>
<ol>
<li>The <code>presentAlertSheetLogout()</code> function not exist we need to create it  </li>
<li>The <code>viewControllerToPresent</code> property not exist we also need to create it  </li>
</ol>
<p>Fix the error for Xcode to compile<br />Create the <code>presentAlertSheetLogout()</code> function  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-keyword">private</span>(<span class="hljs-keyword">set</span>) <span class="hljs-keyword">var</span> alertSheet: <span class="hljs-type">UIAlertController?</span>
  ...
  <span class="hljs-meta">@objc</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
      <span class="hljs-comment">// Do nothing want to see a failed test first</span>
  }
}
</code></pre>
<p>Create the <code>viewControllerToPresent</code> property</p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UINavigationControllerSpy</span>: <span class="hljs-title">UINavigationController</span> </span>{
    ...
    <span class="hljs-keyword">var</span> viewControllerToPresent = <span class="hljs-type">UIViewController</span>()
    ...
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">present</span><span class="hljs-params">(<span class="hljs-number">_</span> viewControllerToPresent: UIViewController, animated flag: Bool, completion: <span class="hljs-params">(<span class="hljs-params">()</span></span></span></span> -&gt; <span class="hljs-type">Void</span>)? = <span class="hljs-literal">nil</span>) {
      <span class="hljs-keyword">self</span>.viewControllerToPresent = viewControllerToPresent
      <span class="hljs-keyword">self</span>.isAnimate = flag
    }
    ...
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: ("nil") is not equal to ("Optional("presentAlertSheetLogout")") - Expect an action to present the logout view</em><br /><em>XCTUnwrap failed: expected non-nil value of type "UIAlertController" - Expect the view to present is of type UIAlertController</em>  </p>
<p>Let’s make it pass<br />First add a <code>Selector</code> for item button action  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    <span class="hljs-keyword">let</span> infosViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfosView</span>())
    infosViewController.title = <span class="hljs-string">"Infos"</span>
    👇    
    <span class="hljs-keyword">let</span> logoutItem = <span class="hljs-type">UIBarButtonItem</span>(image: <span class="hljs-type">UIImage</span>(systemName: <span class="hljs-string">"arrowshape.turn.up.left.circle"</span>),
                                     style: .plain,
                                     target: <span class="hljs-keyword">self</span>,
                                     action: #selector(presentAlertSheetLogout))
    logoutItem.tintColor = .red
    infosViewController.navigationItem.rightBarButtonItem = logoutItem
    navigationController.setViewControllers([infosViewController], animated: animated)
    updateUserAsNotFirstLogin()
</code></pre>
<p>Second create and present the <code>UIAlertController</code>  </p>
<pre><code class="lang-swift">  <span class="hljs-meta">@objc</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
    alertSheet = <span class="hljs-type">UIAlertController</span>(title: <span class="hljs-literal">nil</span>, message: <span class="hljs-literal">nil</span>, preferredStyle: .actionSheet)

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> alertSheet = alertSheet {
      navigationController.present(alertSheet, animated: <span class="hljs-literal">true</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Infos nav bar right button action present an alert sheet
</pre>

<hr />
<p>Continue with this requirement for infos nav bar title </p>
<pre>
 ========= INFOS
   [ ] Alert sheet have a title (no message)
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_presentAlertSheetLogout_alertSheetWithTitleAndNoMessage</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.presentAlertSheetLogout()

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.title, <span class="hljs-string">"Want to logout?"</span>, <span class="hljs-string">"Expect a title"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.message, <span class="hljs-literal">nil</span>, <span class="hljs-string">"Expect no message"</span>)
  }
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: ("nil") is not equal to ("Optional("Want to logout?")") - Expect a title</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Want to logout?"</span> 👈           
    alertSheet = <span class="hljs-type">UIAlertController</span>(title: title 👈, message: <span class="hljs-literal">nil</span>, preferredStyle: .actionSheet)

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> alertSheet = alertSheet {
      navigationController.present(alertSheet, animated: <span class="hljs-literal">true</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Alert sheet have a title (no message)
</pre>

<hr />
<p>Continue with this requirement for alert and cancel action</p>
<pre>
 ========= INFOS
   [ ] Alert sheet have a cancel action (user can dismiss)
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_presentAlertSheetLogout_alertSheetWithCancelAction</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.presentAlertSheetLogout()

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.actions[<span class="hljs-number">0</span>].style, .cancel, <span class="hljs-string">"Expect to have a cancel action"</span>)
  }
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: throwing "**</em> -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray" - Expect to have a cancel action*  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Want to logout?"</span>
    alertSheet = <span class="hljs-type">UIAlertController</span>(title: title, message: <span class="hljs-literal">nil</span>, preferredStyle: .actionSheet) 
    <span class="hljs-keyword">let</span> cancelAction = <span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Cancel"</span>, style: .cancel, handler: <span class="hljs-literal">nil</span>) 👈
<span class="hljs-keyword">self</span>.logout() })
    alertSheet?.addAction(cancelAction) 👈

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> alertSheet = alertSheet {
      navigationController.present(alertSheet, animated: <span class="hljs-literal">true</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Alert sheet have a cancel action (user can dismiss)
</pre>

<hr />
<p>Continue with this requirement for  </p>
<pre>
 ========= INFOS
   [ ] Alert sheet have a logout action
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_presentAlertSheetLogout_alertSheetWithLogoutAction</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.presentAlertSheetLogout()

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.actions[<span class="hljs-number">1</span>].style, .destructive, <span class="hljs-string">"Expect to have a destructive action for the logout"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(alertController.actions[<span class="hljs-number">1</span>].title, <span class="hljs-string">"Logout"</span>, <span class="hljs-string">"Expect to have a title"</span>)
  }
</code></pre>
<p>Run the test and it fails<br /><em>index 1 beyond bounds [0 .. 0]" - Expect to have a destructive action for the logout</em><br /><em>index 1 beyond bounds [0 .. 0]" - Expect to have a title</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Want to logout?"</span>
    alertSheet = <span class="hljs-type">UIAlertController</span>(title: title, message: <span class="hljs-literal">nil</span>, preferredStyle: .actionSheet)
    <span class="hljs-keyword">let</span> cancelAction = <span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Cancel"</span>, style: .cancel, handler: <span class="hljs-literal">nil</span>)
    <span class="hljs-keyword">let</span> logoutAction = <span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Logout"</span>, style: .destructive, handler: { <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> }) 👈

    alertSheet?.addAction(cancelAction)
    alertSheet?.addAction(logoutAction) 👈

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> alertSheet = alertSheet {
      navigationController.present(alertSheet, animated: <span class="hljs-literal">true</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= LOGIN
 [✅] Alert sheet have a logout action
</pre>

<hr />
<p>Continue with this requirement for logout confirmation  </p>
<pre>
 ========= INFOS
   [ ] Confirm logout set login as root with no animation
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_presentAlertSheetLogout_confirmLogoutSetLoginAsRootWithNoAnimation</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.presentAlertSheetLogout()

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>)

    alertController.actions[<span class="hljs-number">1</span>].simulateTriggerAction() <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers.first <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">LoginView</span>&gt;, <span class="hljs-string">"Expect login view as root view controller"</span>)
    <span class="hljs-type">XCTAssertFalse</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect no animation when displaying the login view"</span>)
  }
</code></pre>
<ol>
<li>The <code>UIAlertAction</code> has no member <code>simulateTriggerAction()</code> we need to create it  </li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">UIAlertAction</span> </span>{
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">AlertHandler</span> = <span class="hljs-meta">@convention</span>(block) (<span class="hljs-type">UIAlertAction</span>) -&gt; <span class="hljs-type">Void</span>
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">simulateTriggerAction</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> block = value(forKey: <span class="hljs-string">"handler"</span>) <span class="hljs-keyword">else</span> {
      <span class="hljs-type">XCTFail</span>(<span class="hljs-string">"Expect value for key handler"</span>)
      <span class="hljs-keyword">return</span>
    }
    <span class="hljs-keyword">let</span> handler = <span class="hljs-built_in">unsafeBitCast</span>(block <span class="hljs-keyword">as</span> <span class="hljs-type">AnyObject</span>, to: <span class="hljs-type">AlertHandler</span>.<span class="hljs-keyword">self</span>)
    handler(<span class="hljs-keyword">self</span>)
  }
}
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertTrue failed - Expect login view as root view controller</em><br /><em>XCTAssertFalse failed - Expect no animation when displaying the login view</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  👇
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">logout</span><span class="hljs-params">()</span></span> { 
    setLoginViewAsRoot()
  }
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">presentAlertSheetLogout</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Want to logout?"</span>
    alertSheet = <span class="hljs-type">UIAlertController</span>(title: title, message: <span class="hljs-literal">nil</span>, preferredStyle: .actionSheet)
    <span class="hljs-keyword">let</span> cancelAction = <span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Cancel"</span>, style: .cancel, handler: <span class="hljs-literal">nil</span>)
    <span class="hljs-keyword">let</span> logoutAction = <span class="hljs-type">UIAlertAction</span>(title: <span class="hljs-string">"Logout"</span>, style: .destructive, handler: { <span class="hljs-number">_</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">self</span>.logout() 👈 })

    alertSheet?.addAction(cancelAction)
    alertSheet?.addAction(logoutAction)

    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> alertSheet = alertSheet {
      navigationController.present(alertSheet, animated: <span class="hljs-literal">true</span>)
    }
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Confirm logout set login as root with no animation
</pre>

<hr />
<p>Continue with this requirement for logout user that login again display the infos view</p>
<pre>
 ========= LOGIN
   [ ] Login user after a logout set infos view as root (no onboarding)
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_login_onLogoutLoginAgainSetInfosAsRootWithAnimation</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> userIsNotLogin = <span class="hljs-literal">false</span>
    <span class="hljs-keyword">let</span> userIsFirstLogin = <span class="hljs-literal">true</span>
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT(isLogin: userIsNotLogin,
                                       isFirstLogin: userIsFirstLogin)

    sut.login() <span class="hljs-comment">// Display onboarding view</span>
    sut.validateOnboarding() <span class="hljs-comment">// Display infos view</span>
    sut.presentAlertSheetLogout() <span class="hljs-comment">// Display logout action</span>

    <span class="hljs-keyword">let</span> alertController = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.viewControllerToPresent <span class="hljs-keyword">as</span>? <span class="hljs-type">UIAlertController</span>, <span class="hljs-string">"Expect the view to present is of type UIAlertController"</span>)

    alertController.actions[<span class="hljs-number">1</span>].simulateTriggerAction() <span class="hljs-comment">// Logout display login view</span>
    sut.login() <span class="hljs-comment">// Display infos view (not onboarding)</span>

    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.controllers.first <span class="hljs-keyword">is</span> <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">InfosView</span>&gt;, <span class="hljs-string">"Expect infos view visible"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when display infos view"</span>)
}
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertTrue failed - Expect infos view visible</em><br /><em>XCTAssertTrue failed - Expect animation when display infos view</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">if</span> isFirstLogin {
      displayOnboardingView()
    } <span class="hljs-keyword">else</span> {
      setInfosViewAsRoot(animated: <span class="hljs-literal">true</span>) 👈
    }
  }
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">setInfosViewAsRoot</span><span class="hljs-params">(animated: Bool = <span class="hljs-literal">false</span>)</span></span> {
    ...
    updateUserAsNotFirstLogin()
  }
  <span class="hljs-comment">// MARK: Helpers</span>

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateUserAsNotFirstLogin</span><span class="hljs-params">()</span></span> {
    isFirstLogin = <span class="hljs-literal">false</span>
  }
  ...
}
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= INFOS
 [✅] Login user after a logout set infos view as root (no onboarding)
</pre>

<hr />
<p>I let you those requirements as an exercise<br />They have been already made for other view  </p>
<pre>
// ========= INFOS DETAILS
// [] Infos details can push to new info view
// [] Infos details nav bar have a title
// [] Infos details nav bar have a right button for create new info
</pre>

<hr />
<p>Continue with this requirement for  </p>
<pre>
 ========= INFOS DETAILS
   [ ] Infos details nav bar have a back button (user can pop back)
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_displayInfoDetails_navBarWithBackButton</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> selectedInfo = <span class="hljs-type">Info</span>(title: <span class="hljs-string">"A title info"</span>) <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT(isLogin: <span class="hljs-literal">true</span>, isFirstLogin: <span class="hljs-literal">false</span>)

    sut.displayInfoDetails(<span class="hljs-keyword">for</span>: selectedInfo)

    <span class="hljs-keyword">let</span> controller = <span class="hljs-keyword">try</span> <span class="hljs-type">XCTUnwrap</span>(navigationSpy.controllers[<span class="hljs-number">1</span>])
    <span class="hljs-type">XCTAssertTrue</span>(controller.navigationItem.hidesBackButton == <span class="hljs-literal">false</span>, <span class="hljs-string">"Expect that nav bar display a back button"</span>)
  }
</code></pre>
<ol>
<li>The <code>Info</code> type not exist we need to create it    </li>
</ol>
<p>Fix the error for Xcode to compile    </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Info</span>: <span class="hljs-title">Equatable</span> </span>{
    <span class="hljs-keyword">let</span> title: <span class="hljs-type">String</span>
}
</code></pre>
<p>Run the test and it succeed<br />Ok cool we didn't change anything<br />But the test is passing<br />Why? 🤔<br />Because a nav bar displays the back button by default<br />But can we trust a test that we didn't see failing?<br />Of course no!<br />To be sure I testing the right behaviour<br />I always need to see a failing test  </p>
<p>Ok let's make this test fails<br />Hide the back button  </p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">displayInfoDetails</span><span class="hljs-params">(<span class="hljs-keyword">for</span> info: Info)</span></span> {
    <span class="hljs-keyword">let</span> infoDetailsViewController = <span class="hljs-type">UIHostingController</span>(rootView: <span class="hljs-type">InfoDetailsView</span>(info: info))
    infoDetailsViewController.title = <span class="hljs-string">"Info Details"</span>

    <span class="hljs-keyword">let</span> createItem = <span class="hljs-type">UIBarButtonItem</span>(image: <span class="hljs-type">UIImage</span>(systemName: <span class="hljs-string">"plus"</span>), style: .plain, target: <span class="hljs-keyword">self</span>, action: #selector(displayNewInfo))
    createItem.tintColor = .blue
    infoDetailsViewController.navigationItem.rightBarButtonItem = createItem
    infoDetailsViewController.navigationItem.setHidesBackButton(<span class="hljs-literal">true</span> 👈,  animated: <span class="hljs-literal">false</span>)
    navigationController.pushViewController(infoDetailsViewController, animated: <span class="hljs-literal">true</span>)
  }
</code></pre>
<p>Run tests<br />If now failed<br /><em>XCTAssertTrue failed - Expect that nav bar display a back button</em><br />Perfect that's what we want<br />I testing the right behaviour<br />I revert this change and make tests succeed again  </p>
<p>Can mark this requirement as done.  </p>
<pre>
 ========= INFOS DETAILS
 [✅] Infos details nav bar have a back button (user can pop back)
</pre>

<hr />
<p>I let you those requirements as an exercise<br />They have been already made for others views  </p>
<pre>
========= NEW INFOS
[ ] New info nav bar have a title
[ ] New info nav bar have a back button (user can pop back)
</pre>

<hr />
<p>Continue with this requirement that go back to first view  </p>
<pre>
 ========= NEW INFOS
   [ ] Create new info pop to the root view (infos view)
</pre>

<p>As usual write the test first  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_popToRoot_popBackToRootViewWithAnimation</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">throws</span> {
    <span class="hljs-keyword">let</span> (sut, navigationSpy) = makeSUT()

    sut.popToRoot() <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertEqual</span>(navigationSpy.popToRootViewControllerCallCount, <span class="hljs-number">1</span>, <span class="hljs-string">"Expect that pop to root function of the navigation controller was called"</span>) <span class="hljs-comment">// 2</span>
    <span class="hljs-type">XCTAssertTrue</span>(navigationSpy.isAnimate, <span class="hljs-string">"Expect animation when go back"</span>)
  }
</code></pre>
<ol>
<li>The <code>popToRoot()</code> function not exist we need to create it    </li>
<li>The <code>popToRootViewControllerCallCount</code> property of the <code>navigationSpy</code> not exist we need to create it  </li>
</ol>
<p>Fix the error for Xcode to compile<br />Start with <code>popToRoot()</code> function</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NavigationService</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">popToRoot</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Do nothing want to see a failed test first</span>
  }
  ...
}
</code></pre>
<p>Now the <code>popToRootViewControllerCallCount</code> property</p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UINavigationControllerSpy</span>: <span class="hljs-title">UINavigationController</span> </span>{
    ...
    <span class="hljs-keyword">var</span> popToRootViewControllerCallCount = <span class="hljs-number">0</span>
    ...
    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">popToRootViewController</span><span class="hljs-params">(animated: Bool)</span></span> -&gt; [<span class="hljs-type">UIViewController</span>]? {
      <span class="hljs-keyword">self</span>.popToRootViewControllerCallCount += <span class="hljs-number">1</span>
      <span class="hljs-keyword">self</span>.isAnimate = animated
      <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
    }
  }
</code></pre>
<p>Run the test and it fails<br /><em>XCTAssertEqual failed: ("0") is not equal to ("1") - Expect that pop to root function of the navigation controller was called</em><br /><em>XCTAssertTrue failed - Expect animation when go back</em>  </p>
<p>Let’s make it pass  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">popToRoot</span><span class="hljs-params">()</span></span> {
    navigationController.popToRootViewController(animated: <span class="hljs-literal">true</span>)  👈
  }
</code></pre>
<p>Run tests<br />They are passing<br />Can mark this requirement as done.  </p>
<pre>
 ========= NEW INFOS
 [✅] Create new info pop to the root view (infos view)
</pre>

<hr />
<p>All behaviour are tested<br />Cool 😎 !!  </p>
<pre>
 ========= LOGIN
 [✅] On init user not login set login view as root with no animation
   [✅] User first login push to the onboarding view
     [✅] Validate onboarding set the infos view as root with no animation
 [✅] On init user login set infos view as root with no animation

 ========= INFOS
 [✅] Infos can push to info details view
 [✅] Infos nav bar have a title
 [✅] Infos nav bar have a right button for logout
   [✅] Infos nav bar right button action present an alert sheet
     [✅] Alert sheet have a title (no message)
     [✅] Alert sheet have a cancel action (user can dismiss)
     [✅] Alert sheet have a logout action
       [✅] Confirm logout set login as root with no animation
         [✅] Login user after a logout set infos view as root (no onboarding)

 ========= INFOS DETAILS
 [✅] Infos details can push to new info view
 [✅] Infos details nav bar have a title
 [✅] Infos details nav bar have a back button (user can pop back)
 [✅] Infos details nav bar have a right button for create new info

 ========= NEW INFOS
 [✅] New info nav bar have a title
 [✅] New info nav bar have a back button (user can pop back)
 [✅] Create new info pop to the root view (infos view)
</pre>

<hr />
<p>Now the integration part<br />How SwiftUI view will use this <code>UINavigationController</code> from <code>UIKit</code><br />Let's see the <code>SwiftUINavigationApp</code> that is the root  (entry point of the app)  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SwiftUINavigationApp</span>: <span class="hljs-title">App</span> </span>{
    <span class="hljs-keyword">var</span> body: some <span class="hljs-type">Scene</span> {
        <span class="hljs-type">WindowGroup</span> {
          <span class="hljs-type">LoginView</span>()
        }
    }
}
</code></pre>
<p>Only the login view will display if run the app<br />Without any nav bar<br />We need a way to inject the <code>UIKit</code> nav bar to a SwiftUI view<br />This a job for the <code>UIViewControllerRepresentable</code><br />That can convert any <code>UIViewController</code> to a SwiftUI view<br />As <code>UINavigationController</code> is a subclass of <code>UIViewController</code><br />We can inject the <code>UINavigationController</code> this way  </p>
<p>First create the <code>NavigationControllerSwiftUI</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">NavigationControllerSwiftUI</span>: <span class="hljs-title">UIViewControllerRepresentable</span> </span>{
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">UIViewControllerType</span> = <span class="hljs-type">UINavigationController</span>
  <span class="hljs-keyword">let</span> navigationService: <span class="hljs-type">NavigationService</span>

  <span class="hljs-keyword">init</span>(navigationService: <span class="hljs-type">NavigationService</span>) {
    <span class="hljs-keyword">self</span>.navigationService = navigationService
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeUIViewController</span><span class="hljs-params">(context: Context)</span></span> -&gt; <span class="hljs-type">UIViewControllerType</span> {
    <span class="hljs-keyword">return</span> navigationService.navigationController
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateUIViewController</span><span class="hljs-params">(<span class="hljs-number">_</span> uiViewController: UIViewControllerType, context: Context)</span></span> {}
}
</code></pre>
<p>Next use it in the <code>SwiftUINavigationApp</code><br />Of course the logic to init the <code>NavigationService</code> must be tested<br />And in a real app must call a service to init his parameters<br />But we are focusing here on the navigation logic<br />(And this article is already long enough right? 😅)  </p>
<pre><code class="lang-swift">@main
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SwiftUINavigationApp</span>: <span class="hljs-title">App</span> </span>{
    <span class="hljs-keyword">let</span> navigationService = <span class="hljs-type">NavigationService</span>(navigationController: <span class="hljs-type">UINavigationController</span>(), isLogin: <span class="hljs-literal">false</span>, isFirstLogin: <span class="hljs-literal">true</span>)

    <span class="hljs-keyword">var</span> body: some <span class="hljs-type">Scene</span> {
        <span class="hljs-type">WindowGroup</span> {
          <span class="hljs-type">NavigationControllerSwiftUI</span>(navigationService: navigationService)
            .edgesIgnoringSafeArea(.top)
            .environmentObject(navigationService) <span class="hljs-comment">// 1</span>
        }
    }
}
</code></pre>
<p>Inject the <code>navigationService</code> as <code>environmentObject</code><br />So the <code>NavigationService</code> can be accessible from any subview<br />Here is an example for the <code>LoginView</code></p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">LoginView</span>: <span class="hljs-title">View</span> </span>{
  @<span class="hljs-type">EnvironmentObject</span> <span class="hljs-keyword">var</span> navigationService: <span class="hljs-type">NavigationService</span> <span class="hljs-comment">// 1</span>

  <span class="hljs-keyword">var</span> body: some <span class="hljs-type">View</span> {
    <span class="hljs-type">CustomButton</span>(title: <span class="hljs-string">"Login"</span>) {
      navigationService.login() <span class="hljs-comment">// 2</span>
    }
      .navigationBarHidden(<span class="hljs-literal">true</span>) <span class="hljs-comment">// 3</span>
  }
}
</code></pre>
<ol>
<li>The <code>NavigationService</code> can be access via the <code>@EnvironmentObject</code> variable  </li>
<li>Now the <code>navigationService</code> is used on login button action  </li>
<li>Hide the nav bar from the SwiftUI view, get crash when try to handle it using <code>UIKit</code>  </li>
</ol>
<p>I make this for all SwiftUI views<br />Let's see if hour logic cover by test is working<br />Running the app<br />Everything working fine<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655670778205/xmReIw6tN.gif" alt="Simulator Screen Recording - iPhone 11 - 2022-06-19 at 22.09.53.gif" class="image--center mx-auto" /></p>
<hr />
<p>This is the end of this article<br />You see how convenient it is to have the navigation logic in a central place<br />Easy to scale, to test, to maintain, ...<br />Hope you enjoy it<br />Of course you also use the <code>UINavigationBarController</code> only for navigation purposes<br />And get a custom nav bar made using SwiftUI view  </p>
<p>That it !!</p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - Test drive the logic inside a view using TDD]]></title><description><![CDATA[You have this view to integrate Specs for this design look like this: But there is a problem with this designIt's only takes into account the happy pathBut…]]></description><link>https://swiftuicentral.com/swiftui-test-drive-the-logic-inside-a-view-using-tdd</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-test-drive-the-logic-inside-a-view-using-tdd</guid><category><![CDATA[Swift]]></category><category><![CDATA[SwiftUI]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Mon, 30 May 2022 20:13:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/npxXWgQ33ZQ/upload/v1653910647633/BoAoageX8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-test-behavior-inside-a-swiftui-view">Problem: How test behavior inside a SwiftUI view ?</h2>
<h3 id="heading-solution-extract-all-the-logic-in-a-viewmodel-and-test-drive-only-the-behaviour-using-the-tdd-process">Solution: Extract all the logic in a ViewModel and test drive only the behaviour using the TDD process !</h3>
<p>You have this view to integrate 
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653826763460/fPoQaiPKf.png" alt="image.png" class="image--center mx-auto" /></p>
<p>Specs for this design look like this:  </p>
<pre>
- [ ] Display favorites/restaurants  
</pre>

<p>But there is a problem with this design<br />It's only takes into account the happy path<br />But a lot of things can go wrong here<br />What happen:</p>
<ul>
<li>On slow init restaurants (slow server response)?  </li>
<li>If loading restaurants failed (server error)?  </li>
<li>If the server return an empty response (no restaurants)?  </li>
<li>On slow update for favorite status (slow server response) ?  </li>
<li>If favorite status failed (server error)?  </li>
</ul>
<p>After ask those questions to the team<br />I have more infos to understand what I'm trying to build<br />Here are the new specs:  </p>
<pre>
[ ] On init restaurants/favorites are loading  
    [ ] If init succeed but no restaurants, display an image with a message  
     [ ] If init succeed favorites/restaurants are displayed  
     [ ] User can select favorites/restaurant to display details view  
     [ ] User can add a restaurant to favorites  
        [ ] Status is pending (UI loader is display)  
        [ ] If success delete from restaurants and add to favorites  
        [ ] If failed deliver an error  
    [ ] User can delete restaurant from favorites  
        [ ] Status is pending (UI loader is display)  
        [ ] If success delete from favorites and add to restaurants
        [ ] If failed deliver an error  
    [ ] If init failed (at least one request failed) an error message is deliver  
        [ ] User can retry if load failed  
</pre>

<p>Knowing what we want to build<br />Let's test drive this implementation using TDD<br />Every of those specs must have a corresponding test</p>
<hr />
<p>Start with the first one</p>
<pre>
[ ] On init restaurants/favorites are loading  
</pre>

<p>With this test:</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliversStatusIsPending</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">RestaurantViewModel</span>() <span class="hljs-comment">// 1</span>

    sut.load() <span class="hljs-comment">// 2</span>

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, .pending) <span class="hljs-comment">// 3</span>
  }
</code></pre>
<ol>
<li>The <code>RestaurantViewModel</code> type not exist</li>
<li>The SUT doesn't have a <code>load()</code> function</li>
<li>The status <code>.pending</code> not exist </li>
</ol>
<p>Write some code to make the test pass</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span> </span>{
    <span class="hljs-keyword">case</span> pending
  }

  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> status: <span class="hljs-type">Status</span> = .pending

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">()</span></span> {
    status = .pending
  }
}
</code></pre>
<p>Test succeeded<br />First requirement done  </p>
<pre>
[✅] On init restaurants/favorites are loading  
</pre>

<hr />
<p>Now test the error case  </p>
<pre>
    [ ] If init failed (at least one request failed) an error message is deliver  
        [ ] User can retry if load failed  
</pre>

<p>Like to start with errors<br />Don't have to worry about them later:  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliversErrorOnLoadFailure</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> error = <span class="hljs-type">NSError</span>(domain: <span class="hljs-string">"any error"</span>, code: <span class="hljs-number">404</span>)
    <span class="hljs-keyword">let</span> errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>, message: <span class="hljs-string">"Error 404"</span>, isRetry: <span class="hljs-literal">true</span>)
    <span class="hljs-keyword">let</span> service = <span class="hljs-type">RestaurantService</span>() <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">RestaurantViewModel</span>(service: service)

    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect load completion"</span>)

    sut.load {
      exp.fulfill()
    }

    service.completeWithError(error) <span class="hljs-comment">// 2</span>

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.title, errorDetails.title, <span class="hljs-string">"Expect title update"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.message, errorDetails.message, <span class="hljs-string">"Expect message update"</span>)
    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.isRetry, errorDetails.isRetry, <span class="hljs-string">"Expect is retry update"</span>)
    <span class="hljs-type">XCTAssertTrue</span>(sut.isPresentAlert, <span class="hljs-string">"Expect that setting the error details update this property"</span>)
  }
</code></pre>
<ol>
<li>The <code>service</code> will be the futur object that handles API request</li>
<li>The <code>service</code> simulate a load completion with an error</li>
</ol>
<p>Now fix the compiler error<br />The <code>ErrorDetails</code> type not exist  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ErrorDetails</span> </span>{
  <span class="hljs-keyword">let</span> title: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> message: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> isRetry: <span class="hljs-type">Bool</span>
}
</code></pre>
<p>The <code>RestaurantService</code> not exist<br />It also needs functions called <code>completeWithError()</code> and <code>load()</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantService</span> </span>{
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">LoadCompletions</span> = (<span class="hljs-type">Result</span>&lt;(restaurants: [<span class="hljs-type">Restaurant</span>],
                                       favorites: [<span class="hljs-type">Favorite</span>]), <span class="hljs-type">Error</span>&gt;) -&gt; <span class="hljs-type">Void</span>

  <span class="hljs-keyword">var</span> loadCompletions = [<span class="hljs-type">LoadCompletions</span>]()

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping LoadCompletions)</span></span> {
    loadCompletions.append(completion) <span class="hljs-comment">// 1</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
    loadCompletions[index](.failure(error)) <span class="hljs-comment">// 2</span>
  }
}
</code></pre>
<ol>
<li>Everytime the <code>load()</code> function is called, I accumulate the completion  </li>
<li>Access the completion and send a <code>.failure(error)</code> message  </li>
</ol>
<p>Inject the <code>RestaurantService</code> in the <code>RestaurantViewModel</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-keyword">let</span> service: <span class="hljs-type">RestaurantService</span>
  ...
  <span class="hljs-keyword">init</span>(service: <span class="hljs-type">RestaurantService</span>) {
    <span class="hljs-keyword">self</span>.service = service
  }
  ...
}
</code></pre>
<p>Add a completion to the load function of the SUT (<code>RestaurantViewModel</code>)<br />To access to the result when complete  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
</code></pre>
<p>Add the <code>isPresentAlert</code> and <code>errorDetails</code> properties  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> isPresentAlert = <span class="hljs-literal">false</span>
  <span class="hljs-keyword">var</span> errorDetails: <span class="hljs-type">ErrorDetails?</span> {
    <span class="hljs-keyword">didSet</span> { updateAlertVisibility() } <span class="hljs-comment">// 1</span>
  }
  ...

  <span class="hljs-comment">// MARK: - Helpers</span>

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateAlertVisibility</span><span class="hljs-params">()</span></span> {
    isPresentAlert = errorDetails == <span class="hljs-literal">nil</span> ? <span class="hljs-literal">false</span> : <span class="hljs-literal">true</span>
  }
}
</code></pre>
<ol>
<li>The property <code>isPresentAlert</code> need to be update according to the <code>errorDetails</code> state   </li>
</ol>
<p>Now make the test pass<br />Updating <code>errorDetails</code> and <code>isPresentAlert</code> properties<br />When loading failed  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    status = .pending

    service.load { [<span class="hljs-keyword">weak</span> <span class="hljs-keyword">self</span>] result <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">switch</span> result {
      <span class="hljs-keyword">case</span> .failure(<span class="hljs-keyword">let</span> error <span class="hljs-keyword">as</span> <span class="hljs-type">NSError</span>):
        <span class="hljs-keyword">self</span>?.errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>,
                                         message: <span class="hljs-string">"Error \(error.code)"</span>,
                                         isRetry: <span class="hljs-literal">true</span>)
      <span class="hljs-keyword">case</span> .success:
        <span class="hljs-keyword">break</span>
      }
      completion()
    }
  }
  ...
}
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [✅] If init failed (at least one request failed) an error message is deliver  
        [✅] User can retry if load failed  
</pre>

<hr />
<p>Simplify the test setup<br />Extract it to the <code>makeSUT()</code> function  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeSUT</span><span class="hljs-params">()</span></span> -&gt; (sut: <span class="hljs-type">RestaurantViewModel</span>, service: <span class="hljs-type">RestaurantService</span>) {
    <span class="hljs-keyword">let</span> service = <span class="hljs-type">RestaurantService</span>()
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">RestaurantViewModel</span>(service: service)
    <span class="hljs-keyword">return</span> (sut, service)
  }
</code></pre>
<p>Used like this in test  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliversErrorOnRequestFailure</span><span class="hljs-params">()</span></span> {
    ...
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()
    ...
}
</code></pre>
<hr />
<p>Now the success loading with empty restaurants  </p>
<pre>
  [ ] If init succeed but no restaurants, display an image with a message  
</pre>

<p>Start writing a failing test  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliverEmptyMessageWhenCompleteWithEmptyRestaurantsAndFavorites</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> emptyRestaurants = [<span class="hljs-type">Restaurant</span>]()
    <span class="hljs-keyword">let</span> emptyFavorites = [<span class="hljs-type">Favorite</span>]()
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()

    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect load completion"</span>)

    sut.load {
      exp.fulfill()
    }

    service.completeSuccessfullyWith(restaurants: emptyRestaurants,
                                     favorites: emptyFavorites) <span class="hljs-comment">// 1</span>

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, .empty) <span class="hljs-comment">// 2</span>
  }
</code></pre>
<ol>
<li>The function <code>completeSuccessfullyWith</code> not exist  </li>
<li>The <code>.empty</code> case not exist</li>
</ol>
<p>Add the <code>completeSuccessfullyWith</code> to the <code>service</code>  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeSuccessfullyWith</span><span class="hljs-params">(restaurants: [Restaurant], favorites: [Favorite], at index: Int = <span class="hljs-number">0</span>)</span></span> {
    loadCompletions[index](.success((restaurants: restaurants,
                                     favorites: favorites)))
  }
</code></pre>
<p>Add the <code>.empty</code> case to the status  </p>
<pre><code class="lang-swift">  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span> </span>{
    <span class="hljs-keyword">case</span> pending
    <span class="hljs-keyword">case</span> empty
  }
</code></pre>
<p>The test failed<br /><em>XCTAssertEqual failed: ("pending") is not equal to ("empty")</em></p>
<p>Let's make it pass<br />Update the SUT to handle the <code>.success</code> case  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    status = .pending

    service.load { [<span class="hljs-keyword">weak</span> <span class="hljs-keyword">self</span>] result <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">switch</span> result {
      <span class="hljs-keyword">case</span> .failure(<span class="hljs-keyword">let</span> error <span class="hljs-keyword">as</span> <span class="hljs-type">NSError</span>):
        <span class="hljs-keyword">self</span>?.errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>,
                                         message: <span class="hljs-string">"Error \(error.code)"</span>,
                                         isRetry: <span class="hljs-literal">true</span>)
      <span class="hljs-keyword">case</span> .success(<span class="hljs-keyword">let</span> success):
        <span class="hljs-keyword">let</span> isRestaurantEmpty = success.restaurants.isEmpty &amp;&amp; success.favorites.isEmpty

        <span class="hljs-keyword">if</span> isRestaurantEmpty {
          <span class="hljs-keyword">self</span>?.status = .empty
        }
      }
      completion()
    }
  }
</code></pre>
<p>Test are passing   </p>
<hr />
<p>Extract the logic for the empty restaurant tests<br />To avoid repetition<br />And improve test readability  </p>
<pre><code class="lang-swift">  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">expect</span><span class="hljs-params">(<span class="hljs-number">_</span> sut: RestaurantViewModel, toCompleteWith expectedStatus: RestaurantViewModel.Status, when action: <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect load completion"</span>)

    sut.load {
      exp.fulfill()
    }

    action()

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, expectedStatus)
  }
</code></pre>
<p>Refactoring the test  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliverEmptyMessageWhenCompleteWithEmptyRestaurantsAndFavorites</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> emptyRestaurants = [<span class="hljs-type">Restaurant</span>]()
    <span class="hljs-keyword">let</span> emptyFavorites = [<span class="hljs-type">Favorite</span>]()
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()

    expect(
      sut,
      toCompleteWith: .empty,
      when: {
        service.completeSuccessfullyWith(restaurants: emptyRestaurants,
                                         favorites: emptyFavorites)
      })
  }
</code></pre>
<hr />
<p>Now test the happy path<br />Restaurants and favorites are returned properly</p>
<pre>
    [ ] If init succeed favorites/restaurants are displayed (both requests must be successful)  
</pre>

<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_load_deliversLoadedRestaurantsAndFavorites</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> restaurants = [kfc(), burgerKing()] <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> favorites = [mcDonalds()] <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()

    expect(
      sut,
      toCompleteWith: .loaded(restaurants: restaurants,
                              favorites: favorites),
      when: {
        service.completeSuccessfullyWith(restaurants: restaurants,
                                         favorites: favorites)
      })
  }
</code></pre>
<ol>
<li>Restaurants <code>kfc()</code>, <code>burgerKing()</code> and <code>mcDonalds()</code> not exist   </li>
<li>Status <code>.loaded(restaurants:favorites:)</code> not exist    </li>
</ol>
<p>First create fake restaurants  </p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">mcDonalds</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Restaurant</span> {
  .<span class="hljs-keyword">init</span>(imageName: <span class="hljs-string">"mc-donalds"</span>,
        imageNameFavorite: <span class="hljs-string">"mc-donalds-favorite"</span>,
        waitingTime: <span class="hljs-string">"25-35"</span>,
        name: <span class="hljs-string">"McDonald's"</span>,
        rate: <span class="hljs-string">"4.0 Good (500+)"</span>,
        type: <span class="hljs-string">"American, Burgers"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">burgerKing</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Restaurant</span> {
  .<span class="hljs-keyword">init</span>(imageName: <span class="hljs-string">"burger-king"</span>,
        imageNameFavorite: <span class="hljs-string">"burger-king-favorite"</span>,
        waitingTime: <span class="hljs-string">"25-35"</span>,
        name: <span class="hljs-string">"BURGER KING"</span>,
        rate: <span class="hljs-string">"4.3 Very good (500+)"</span>,
        type: <span class="hljs-string">"American, Burgers"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">kfc</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Restaurant</span> {
  .<span class="hljs-keyword">init</span>(imageName: <span class="hljs-string">"kfc"</span>,
        imageNameFavorite: <span class="hljs-string">"kfc-favorite"</span>,
        waitingTime: <span class="hljs-string">"15-25"</span>,
        name: <span class="hljs-string">"KFC"</span>,
        rate: <span class="hljs-string">"4.1 Good (500+)"</span>,
        type: <span class="hljs-string">"Sandwichs, Burgers"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">carls</span><span class="hljs-params">()</span></span> -&gt; <span class="hljs-type">Restaurant</span> {
  .<span class="hljs-keyword">init</span>(imageName: <span class="hljs-string">"carls-jr"</span>,
        imageNameFavorite: <span class="hljs-string">"carls-jr-favorite"</span>,
        waitingTime: <span class="hljs-string">"15-25"</span>,
        name: <span class="hljs-string">"Carl's Jr"</span>,
        rate: <span class="hljs-string">"3.8 Good (61)"</span>,
        type: <span class="hljs-string">"Sandwichs, Burgers"</span>)
}
</code></pre>
<p>Second create the <code>loaded(restaurants:favorites)</code> status  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span> </span>{
    <span class="hljs-keyword">case</span> pending
    <span class="hljs-keyword">case</span> empty
    <span class="hljs-keyword">case</span> loaded(restaurants: [<span class="hljs-type">Restaurant</span>], favorites: [<span class="hljs-type">Favorite</span>])
}
</code></pre>
<p>The compiler returns an another error<br />In the assertion of the helper function<br /><em>Global function 'XCTAssertEqual(<em>:</em>:_:file:line:)' requires that 'RestaurantViewModel.Status' conform to 'Equatable'</em>  </p>
<p>Let's conform to <code>Equatable</code>  </p>
<pre><code class="lang-swift">  <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Status</span>: <span class="hljs-title">Equatable</span> </span>{
    <span class="hljs-keyword">case</span> pending
    <span class="hljs-keyword">case</span> empty
    <span class="hljs-keyword">case</span> loaded(restaurants: [<span class="hljs-type">Restaurant</span>], favorites: [<span class="hljs-type">Favorite</span>])
  }
</code></pre>
<p>Test failed<br /><em>XCTAssertEqual failed: ("pending") is not equal to ("loaded(restaurants: [SwiftUITestDrivenViewTests.Restaurant(imageName: "kfc", imageNameFavorite: "kfc-favorite", waitingTime: "15-25", name: "KFC", rate: "4.1 Good (500+)", type: "Sandwichs, Burgers"), SwiftUITestDrivenViewTests.Restaurant(imageName: "burger-king", imageNameFavorite: "burger-king-favorite", waitingTime: "25-35", name: "BURGER KING", rate: "4.3 Very good (500+)", type: "American, Burgers")], favorites: [SwiftUITestDrivenViewTests.Restaurant(imageName: "mc-donalds", imageNameFavorite: "mc-donalds-favorite", waitingTime: "25-35", name: "McDonald\'s", rate: "4.0 Good (500+)", type: "American, Burgers")])")
</em></p>
<p>Let's make it pass<br />In the <code>.success</code> case add the <code>else</code> condition<br />To handle non empty response  </p>
<pre><code class="lang-swift">      ...
      <span class="hljs-keyword">case</span> .success(<span class="hljs-keyword">let</span> success):
        <span class="hljs-keyword">let</span> isRestaurantEmpty = success.restaurants.isEmpty &amp;&amp; success.favorites.isEmpty

        <span class="hljs-keyword">if</span> isRestaurantEmpty {
          <span class="hljs-keyword">self</span>?.status = .empty
        } <span class="hljs-keyword">else</span> {
          <span class="hljs-keyword">self</span>?.status = .loaded(restaurants: success.restaurants,
                                favorites: success.favorites)
        }
        ...
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [✅] If init succeed favorites/restaurants are displayed (both requests must be successful)  
</pre>

<hr />
<p>Now test the selection of a restaurant  </p>
<pre>
    [ ] User can select favorites/restaurant to display details view  
</pre>

<p>As usual start writing a test  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_selectRestaurant_pushSelectedRestaurantToDetailsView</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> selectedRestaurant = kfc()
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT()

    sut.updateSelected(with: selectedRestaurant) <span class="hljs-comment">// 1</span>

    <span class="hljs-type">XCTAssertEqual</span>(sut.selectedRestaurant, selectedRestaurant) <span class="hljs-comment">// 2</span>
    <span class="hljs-type">XCTAssertTrue</span>(sut.isPushToDetailsView) <span class="hljs-comment">// 3</span>
  }
</code></pre>
<ol>
<li>The SUT don't have a function <code>updateSelected(with:)</code>  </li>
<li>The SUT don't have <code>selectedRestaurant</code> property  </li>
<li>The SUT don't have <code>isPushToDetailsView</code> property  </li>
</ol>
<p>Add them to the SUT<br />And also a private function <code>updateDetailViewVisibility()</code><br />That handle details view visibility  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> isPushToDetailsView = <span class="hljs-literal">false</span>
  <span class="hljs-keyword">private</span>(<span class="hljs-keyword">set</span>) <span class="hljs-keyword">var</span> selectedRestaurant: <span class="hljs-type">Restaurant?</span> {
    <span class="hljs-keyword">didSet</span> { updateDetailViewVisibility() }
  }
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateSelected</span><span class="hljs-params">(with restaurant: Restaurant?)</span></span> {
    selectedRestaurant = restaurant
  }
  ...
  <span class="hljs-comment">// MARK: Helpers</span>
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateDetailViewVisibility</span><span class="hljs-params">()</span></span> {
    isPushToDetailsView = selectedRestaurant == <span class="hljs-literal">nil</span> ? <span class="hljs-literal">false</span> : <span class="hljs-literal">true</span>
  }
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [✅] User can select favorites/restaurant to display details view  
</pre>

<hr />
<p>Test the behavior of adding a restaurant to favorite  </p>
<pre>
     [ ] User can add a restaurant to favorites  
        [ ] Status is pending (UI loader is display)  
        [ ] If success delete from restaurants and add to favorites  
        [ ] If failed deliver an error  
</pre>

<p>Start with the error  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_addToFavorites_deliversErrorOnRequestFailure</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> error = <span class="hljs-type">NSError</span>(domain: <span class="hljs-string">"any error"</span>, code: <span class="hljs-number">404</span>)
    <span class="hljs-keyword">let</span> errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>, message: <span class="hljs-string">"Error 404"</span>, isRetry: <span class="hljs-literal">false</span>)
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()
    <span class="hljs-keyword">let</span> restaurant = kfc()

    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect addToFavorites completion"</span>)

    sut.addToFavorites(restaurant) { <span class="hljs-comment">// 1</span>
      exp.fulfill()
    }

    service.completeAddFavoriteWithError(error) <span class="hljs-comment">// 2</span>

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.title, errorDetails.title)
    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.message, errorDetails.message)
    <span class="hljs-type">XCTAssertEqual</span>(sut.errorDetails?.isRetry, errorDetails.isRetry)
    <span class="hljs-type">XCTAssertTrue</span>(sut.isPresentAlert, <span class="hljs-string">"Expect that setting the error details update this property"</span>)
  }
</code></pre>
<ol>
<li>The SUT don't have the <code>addToFavorites(restaurant:)</code> function  </li>
<li>The service don't have the <code>completeAddFavoriteWithError(error:)</code> function  </li>
</ol>
<p>Add <code>addToFavorites(restaurant:)</code> to the SUT  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addToFavorites</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {

  }
</code></pre>
<p>Add <code>completeAddFavoriteWithError(error:)</code> to the <code>service</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantService</span> </span>{
  ...
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">FavoriteResult</span> = <span class="hljs-type">Result</span>&lt;<span class="hljs-type">Restaurant</span>, <span class="hljs-type">Error</span>&gt;
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">FavoriteCompletions</span> = (<span class="hljs-type">FavoriteResult</span>) -&gt; <span class="hljs-type">Void</span>
  ...
  <span class="hljs-keyword">var</span> addFavoriteCompletions = [<span class="hljs-type">FavoriteCompletions</span>]()
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {
    addFavoriteCompletions.append(completion)
  }
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeAddFavoriteWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
    addFavoriteCompletions[index](.failure(error))
  }
}
</code></pre>
<p>Run tests<br />There is a crash<br /><em>Thread 1: Fatal error: Index out of range</em>  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeAddFavoriteWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
    addFavoriteCompletions[index](.failure(error))
  }
</code></pre>
<p>The <code>addFavoriteCompletions</code> property is empty   </p>
<p>When we check <code>RestaurantViewModel</code><br />The <code>addToFavorites(restaurant:completion:)</code> does nothing  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addToFavorites</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {

  }
</code></pre>
<p>Ok let's fix this   </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addToFavorites</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    service.addFavorite(restaurant) { result <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">switch</span> result {
      <span class="hljs-keyword">case</span> .success:
        <span class="hljs-keyword">break</span>
      <span class="hljs-keyword">case</span> <span class="hljs-keyword">let</span> .failure(error <span class="hljs-keyword">as</span> <span class="hljs-type">NSError</span>):
        <span class="hljs-keyword">self</span>.errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>,
                                         message: <span class="hljs-string">"Error \(error.code)"</span>,
                                         isRetry: <span class="hljs-literal">false</span>)
      }
      completion()
    }
  }
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [ ] User can add restaurant to favorites  
        [ ] Status is pending (UI loader is display)  
        [ ] If success add to favorites and delete from restaurant  
        [✅] If failed deliver an error  
</pre>

<hr />
<p>Now test the add favorite restaurant success case  </p>
<pre>
        [ ] If success add to favorites and delete from restaurant  
</pre>

<p>Start with a test  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_addToFavorites_addToFavoritesDeleteFromRestaurantsOnSuccess</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> restaurant = kfc()
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()
    sut.status = .loaded(restaurants: [restaurant], favorites: [])
    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect load completion"</span>)

    sut.addToFavorites(restaurant) {
      exp.fulfill()
    }

    service.completeAddFavoriteSuccessfullyWith(restaurant) <span class="hljs-comment">// 1</span>

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertEqual</span>(sut.status, .loaded(restaurants: [], favorites: [restaurant]))
  }
</code></pre>
<ol>
<li>The SUT don't have the <code>completeAddFavoriteSuccessfullyWith(restaurant:)</code> function  </li>
</ol>
<p>Add the <code>completeAddFavoriteSuccessfullyWith(restaurant:)</code> to the <code>RestaurantService</code>  </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeAddFavoriteSuccessfullyWith</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, at index: Int = <span class="hljs-number">0</span>)</span></span> {
    addFavoriteCompletions[index](.success(restaurant))
  }
</code></pre>
<p>Test failed<br /><em>XCTAssertEqual failed: ("loaded(restaurants: [SwiftUITestDrivenViewTests.Restaurant(imageName: "kfc", imageNameFavorite: "kfc-favorite", waitingTime: "15-25", name: "KFC", rate: "4.1 Good (500+)", type: "Sandwichs, Burgers")], favorites: [])") is not equal to ("loaded(restaurants: [], favorites: [SwiftUITestDrivenViewTests.Restaurant(imageName: "kfc", imageNameFavorite: "kfc-favorite", waitingTime: "15-25", name: "KFC", rate: "4.1 Good (500+)", type: "Sandwichs, Burgers")])")
</em></p>
<p>The restaurant is not added to the favorite<br />Let's fix this handling the success case   </p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addToFavorites</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    service.addFavorite(restaurant) { result <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">switch</span> result {
      <span class="hljs-keyword">case</span> .success:
        <span class="hljs-keyword">self</span>.updateStatusAddingFavorite(restaurant)
      <span class="hljs-keyword">case</span> <span class="hljs-keyword">let</span> .failure(error <span class="hljs-keyword">as</span> <span class="hljs-type">NSError</span>):
        <span class="hljs-keyword">self</span>.errorDetails = <span class="hljs-type">ErrorDetails</span>(title: <span class="hljs-string">"Request Failed"</span>,
                                         message: <span class="hljs-string">"Error \(error.code)"</span>,
                                         isRetry: <span class="hljs-literal">false</span>)
      }
      completion()
    }
  }
  ...
  <span class="hljs-comment">// MARK: - Helpers</span>
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updateStatusAddingFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant)</span></span> {
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">case</span> <span class="hljs-keyword">var</span> .loaded(restaurants: restaurants, favorites: favorites) = <span class="hljs-keyword">self</span>.status {
      favorites.append(restaurant)
      restaurants.removeAll(<span class="hljs-keyword">where</span>: { $<span class="hljs-number">0</span> == restaurant })
      <span class="hljs-keyword">self</span>.status = .loaded(restaurants: restaurants,
                            favorites: favorites)
    }
  }
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [ ] User can add restaurant to favorites
        [ ] Status is pending (UI loader is display)
        [✅] If success add to favorites and delete from restaurant
        [✅] If failed deliver an error
</pre>

<hr />
<p>Now the pending status for a selected restaurant  </p>
<pre>
        [ ] Status is pending (UI loader is display)  
</pre>

<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_isPending_updatePendingStatusOnFavoriteApiRequest</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> restaurant = kfc()
    <span class="hljs-keyword">let</span> (sut, service) = makeSUT()
    sut.status = .loaded(restaurants: [restaurant], favorites: [])
    <span class="hljs-keyword">let</span> exp = <span class="hljs-type">XCTestExpectation</span>(description: <span class="hljs-string">"Expect delete from favorite to complete"</span>)

    <span class="hljs-type">XCTAssertFalse</span>(sut.isPending(<span class="hljs-keyword">for</span>: restaurant), <span class="hljs-string">"Expect that restaurant is not pending on init"</span>) <span class="hljs-comment">// 1</span>

    sut.addToFavorites(restaurant) {
      exp.fulfill()
    }

    <span class="hljs-type">XCTAssertTrue</span>(sut.isPending(<span class="hljs-keyword">for</span>: restaurant), <span class="hljs-string">"Expect that restaurant is pending because of the running api request"</span>) <span class="hljs-comment">// 1</span>

    service.completeAddFavoriteSuccessfullyWith(restaurant)

    wait(<span class="hljs-keyword">for</span>: [exp], timeout: <span class="hljs-number">1</span>)

    <span class="hljs-type">XCTAssertFalse</span>(sut.isPending(<span class="hljs-keyword">for</span>: restaurant), <span class="hljs-string">"Expect that restaurant is not pending because the api request complete"</span>) <span class="hljs-comment">// 1</span>
  }
</code></pre>
<ol>
<li>The SUT don't have the <code>isPending(for:)</code> function  </li>
</ol>
<p>Add <code>isPending(for:)</code> to the SUT  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  @<span class="hljs-type">Published</span> <span class="hljs-keyword">private</span>(<span class="hljs-keyword">set</span>) <span class="hljs-keyword">var</span> pendingRestaurants = [<span class="hljs-type">Restaurant</span>]()
  ... 
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">isPending</span><span class="hljs-params">(<span class="hljs-keyword">for</span> restaurant: Restaurant)</span></span> -&gt; <span class="hljs-type">Bool</span> {
    pendingRestaurants.<span class="hljs-built_in">contains</span>(restaurant)
  }
  ...
}
</code></pre>
<p>Test failed to the true assertion  </p>
<pre><code class="lang-swift">    <span class="hljs-type">XCTAssertTrue</span>(sut.isPending(<span class="hljs-keyword">for</span>: restaurant), <span class="hljs-string">"Expect that restaurant is pending because of the running api request"</span>)
</code></pre>
<p>Let's make it pass   </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addToFavorites</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping <span class="hljs-params">()</span></span></span> -&gt; <span class="hljs-type">Void</span>) {
    addPending(restaurant)

    service.addFavorite(restaurant) { result <span class="hljs-keyword">in</span>
      <span class="hljs-keyword">self</span>.deletePending(restaurant)
      ...
    }
  }    
  ...    
  <span class="hljs-comment">// MARK: - Helpers</span>
  ...
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addPending</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant)</span></span> {
    pendingRestaurants.append(restaurant)
  }

  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">deletePending</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant)</span></span> {
    pendingRestaurants.removeAll(<span class="hljs-keyword">where</span>: { $<span class="hljs-number">0</span> == restaurant })
  }
}
</code></pre>
<p>Test is passing<br />Checkmark this requirement as done  </p>
<pre>
    [✅] User can add restaurant to favorites  
        [✅] Status is pending (UI loader is display)  
        [✅] If success add to favorites and delete from restaurant  
        [✅] If failed deliver an error  
</pre>

<hr />
<p>Test for favorite deletion  </p>
<pre>
    [ ] User can delete restaurant from favorites  
        [ ] Status is pending (UI loader is display)  
        [ ] If success delete from favorites and add to restaurants
        [ ] If failed deliver an error  
</pre>

<p>I Leave you thoses case as an exercice<br />Because it's the same as addition  </p>
<hr />
<p>All behaviours are now tested  </p>
<pre>
[✅] On init restaurants/favorites are loading  
    [✅] If init succeed but no restaurants, display an image with a message  
    [✅] If init succeed favorites/restaurants are displayed  
    [✅] User can select favorites/restaurant to display details view  
     [✅] User can add a restaurant to favorites  
        [✅] Status is pending (UI loader is display)  
        [✅] If success delete from restaurants and add to favorites  
        [✅] If failed deliver an error  
    [✅] User can delete restaurant from favorites  
        [✅] Status is pending (UI loader is display)  
        [✅] If success delete from favorites and add to restaurants
        [✅] If failed deliver an error  
    [✅] If init failed (at least one request failed) an error message is deliver  
        [✅] User can retry if load failed  
</pre>

<p>We can now extract the production code from the test code<br />In a <code>RestaurantService</code> as a <code>protocol</code>  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">protocol</span> <span class="hljs-title">RestaurantService</span> </span>{
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">LoadCompletions</span> = (<span class="hljs-type">Result</span>&lt;(restaurants: [<span class="hljs-type">Restaurant</span>],
                                       favorites: [<span class="hljs-type">Favorite</span>]), <span class="hljs-type">Error</span>&gt;) -&gt; <span class="hljs-type">Void</span>
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">FavoriteResult</span> = <span class="hljs-type">Result</span>&lt;<span class="hljs-type">Restaurant</span>, <span class="hljs-type">Error</span>&gt;
  <span class="hljs-keyword">typealias</span> <span class="hljs-type">FavoriteCompletions</span> = (<span class="hljs-type">FavoriteResult</span>) -&gt; <span class="hljs-type">Void</span>

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping LoadCompletions)</span></span>
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span>
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">deleteFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span>
}
</code></pre>
<p>The <code>RestaurantService</code> class<br />Now conforms to the protocol<br />And becomes <code>RestaurantServiceSpy</code><br /><code>RestaurantServiceSpy</code> is now a private class<br />In the Helpers section test  </p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span>  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestaurantServiceSpy</span>: <span class="hljs-title">RestaurantService</span> </span>{
    <span class="hljs-keyword">var</span> loadCompletions = [<span class="hljs-type">LoadCompletions</span>]()
    <span class="hljs-keyword">var</span> addFavoriteCompletions = [<span class="hljs-type">FavoriteCompletions</span>]()
    <span class="hljs-keyword">var</span> deleteFavoriteCompletions = [<span class="hljs-type">FavoriteCompletions</span>]()

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping LoadCompletions)</span></span> {
      loadCompletions.append(completion)
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {
      addFavoriteCompletions.append(completion)
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">deleteFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {
      deleteFavoriteCompletions.append(completion)
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
      loadCompletions[index](.failure(error))
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeSuccessfullyWith</span><span class="hljs-params">(restaurants: [Restaurant], favorites: [Favorite], at index: Int = <span class="hljs-number">0</span>)</span></span> {
      loadCompletions[index](.success((restaurants: restaurants,
                                       favorites: favorites)))
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeAddFavoriteWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
      addFavoriteCompletions[index](.failure(error))
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeAddFavoriteSuccessfullyWith</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, at index: Int = <span class="hljs-number">0</span>)</span></span> {
      addFavoriteCompletions[index](.success(restaurant))
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeDeleteFavoriteWithError</span><span class="hljs-params">(<span class="hljs-number">_</span> error: Error, at index: Int = <span class="hljs-number">0</span>)</span></span> {
      deleteFavoriteCompletions[index](.failure(error))
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">completeDeleteFavoriteSuccessfullyWith</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, at index: Int = <span class="hljs-number">0</span>)</span></span> {
      deleteFavoriteCompletions[index](.success(restaurant))
    }
  }
</code></pre>
<hr />
<p>I already create all SwiftUI views required for this app<br />Those views of course called this tested view model</p>
<hr />
<p>Now create a fake service<br />That simulate failed and succeed request<br />Here is the scenario that I want   </p>
<ol>
<li>Load is a failure  </li>
<li>The user retry   </li>
<li>Load is a success  </li>
<li>Restaurants are displayed  </li>
<li>Add/delete a favorite always failed the first time  </li>
<li>After Add/delete a favorite always succeeded   </li>
<li>User can view a details view of a restaurant  </li>
</ol>
<p>Let's create fake service for empty restaurants</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FakeRestaurantService</span>: <span class="hljs-title">RestaurantService</span> </span>{

  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> loadCallCount = <span class="hljs-number">0</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> addFavoriteCallCount = <span class="hljs-number">0</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> deleteFavoriteCallCount = <span class="hljs-number">0</span>

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping LoadCompletions)</span></span> {
    loadCallCount += <span class="hljs-number">1</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">"loadCallCount: \(loadCallCount)"</span>)
    <span class="hljs-keyword">if</span> loadCallCount &lt; <span class="hljs-number">2</span> {
      <span class="hljs-keyword">let</span> error = <span class="hljs-type">NSError</span>(domain: <span class="hljs-string">"any"</span>, code: <span class="hljs-number">404</span>)
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">1000</span>)) {
        completion(.failure(error))
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">2000</span>)) {
        completion(.success((restaurants: [mcDonalds(), kfc(), carls()],
                             favorites: [burgerKing()])))
      }
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {
    addFavoriteCallCount += <span class="hljs-number">1</span>

    <span class="hljs-keyword">if</span> addFavoriteCallCount &lt; <span class="hljs-number">2</span> {
      <span class="hljs-keyword">let</span> error = <span class="hljs-type">NSError</span>(domain: <span class="hljs-string">"any"</span>, code: <span class="hljs-number">400</span>)
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">1000</span>)) {
        completion(.failure(error))
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">1000</span>)) {
        completion(.success(restaurant))
      }
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">deleteFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {
    deleteFavoriteCallCount += <span class="hljs-number">1</span>

    <span class="hljs-keyword">if</span> deleteFavoriteCallCount &lt; <span class="hljs-number">2</span> {
      <span class="hljs-keyword">let</span> error = <span class="hljs-type">NSError</span>(domain: <span class="hljs-string">"any"</span>, code: <span class="hljs-number">404</span>)
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">1000</span>)) {
        completion(.failure(error))
      }
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">1000</span>)) {
        completion(.success(restaurant))
      }
    }
  }
}
</code></pre>
<p>Use this fake service in the live preview   </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">RestaurantsView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-type">RestaurantsView</span>(title: <span class="hljs-string">"Restaurants"</span>,
                    viewModel: .<span class="hljs-keyword">init</span>(service: <span class="hljs-type">FakeRestaurantService</span>()))
  }
}
</code></pre>
<p>Let see it in action in the live preview
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653824965728/3e0FLiZk5.gif" alt="Simulator Screen Recording - iPhone 11 - 2022-05-29 at 13.29.15.gif" class="image--center mx-auto" /></p>
<hr />
<p>Cool we can simulate the behaviour of our use case<br />Without API request<br />No internet connection<br />Even without running a single time the app in the simulator<br />That boost our productivity a lot  </p>
<hr />
<p>Create also a fake service for empty restaurant<br />To check if it also works properly  </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FakeEmptyRestaurantService</span>: <span class="hljs-title">RestaurantService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">load</span><span class="hljs-params">(completion: @escaping LoadCompletions)</span></span> {
    <span class="hljs-type">DispatchQueue</span>.main.asyncAfter(deadline: .now() + .milliseconds(<span class="hljs-number">2000</span>)) {
      completion(.success((restaurants: [],
                           favorites: [])))
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">addFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {}

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">deleteFavorite</span><span class="hljs-params">(<span class="hljs-number">_</span> restaurant: Restaurant, completion: @escaping FavoriteCompletions)</span></span> {}
}
</code></pre>
<p>Use it in the live preview   </p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">RestaurantsView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-type">RestaurantsView</span>(title: <span class="hljs-string">"Restaurants"</span>,
                    viewModel: .<span class="hljs-keyword">init</span>(service: <span class="hljs-type">FakeRestaurantService</span>()))
  }
}
</code></pre>
<p>It's working pretty well<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653826200292/Ar_tPg_G7.gif" alt="Simulator Screen Recording - iPhone 11 - 2022-05-29 at 14.09.46.gif" class="image--center mx-auto" /></p>
<hr />
<p>Thanks to the power of TTD<br />We only take care of the expected behaviour<br />And leave implementation details away<br />Avoid coupling our test with frameworks are other details<br />Making our tests even more powerful<br />Avoid future breaking changes   </p>
<p>That's it !!  </p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - Automate UI regression]]></title><description><![CDATA[Problem: How to automate regression on UI screens? Solution: Snapshot Tests !]]></description><link>https://swiftuicentral.com/swiftui-automate-ui-regression</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-automate-ui-regression</guid><category><![CDATA[Swift]]></category><category><![CDATA[iOS]]></category><category><![CDATA[UI]]></category><category><![CDATA[SwiftUI]]></category><category><![CDATA[TDD (Test-driven development)]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Thu, 21 Apr 2022 20:19:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/z4KhbVhPP7s/upload/v1650572495790/KthyQAjht.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-to-automate-regression-on-ui-screens"><strong>Problem</strong>: How to automate regression on UI screens?</h2>
<h3 id="heading-solution-snapshot-tests"><strong>Solution</strong>: Snapshot Tests !</h3>
<p>SwiftUI and the Live Preview are a good match<br />Thanks to them I was able to quickly build this view:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650539944068/8c94HuMEx.png" alt="image.png" /></p>
<p>The Live Preview is effective for creating views<br />But does not warn in case of regressions<br />So you have to write automated tests  </p>
<p>Tests will be done on the smallest iOS 13 compatible iPhone<br />An iPhone SE  </p>
<p>Import of the <strong>SnapshotTest</strong> library via SPM<br />https://github.com/pointfreeco/swift-snapshot-testing<br />Import the library <strong>into the test target</strong><br /><strong>Not</strong> the app target</p>
<hr />
<p>Import <strong>SnapshotTest</strong> library into test file<br />And create the first snapshot</p>
<pre><code class="lang-swift"><span class="hljs-keyword">import</span> XCTest
<span class="hljs-meta">@testable</span> <span class="hljs-keyword">import</span> SnapshotTest
<span class="hljs-keyword">import</span> SnapshotTesting
<span class="hljs-keyword">import</span> SwiftUI

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StatisticsViewSnapshotTests</span>: <span class="hljs-title">XCTestCase</span> </span>{

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_lightMode</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> viewModel = <span class="hljs-type">StatisticsViewModel</span>()
    <span class="hljs-keyword">let</span> statisticsView = <span class="hljs-type">StatisticsView</span>(viewModel: viewModel)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">UIHostingController</span>(rootView: statisticsView)

    assertSnapshot(matching: sut.rootView, 
                   <span class="hljs-keyword">as</span>: .image(drawHierarchyInKeyWindow: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 1</span>
                              layout: .device(config: .iPhoneSe), 
                              traits: .<span class="hljs-keyword">init</span>(userInterfaceStyle: .light)))
  }
}
</code></pre>
<ol>
<li><code>drawHierarchyInKeyWindow</code> allows to render the view on top of the SwiftUI view<br />This is required or the visual blur effect of the tab bar will not be visible<br />Because this effect is on top at the window level</li>
</ol>
<p>Run the first test<br />It fails:  </p>
<p><strong><em>failed - No reference was found on disk. Automatically recorded snapshot: … </em></strong><br />The first time the test is run<br />The snapshot created cannot be compared with a previous one<br />So he failed<br />But this snapshot has been saved for future comparisons  </p>
<p><strong><em>open "/Users/alexandre/Documents/SnapshotTest/SnapshotTestTests/<strong>Snapshots</strong>/StatisticsViewSnapshotTests/test_lightMode.1.png"</em></strong><br />Path of the saved snapshot<br />Enter this command in Terminal<br />Allows access to the location of the snapshot  </p>
<p><strong><em>Re-run "test" to test against the newly-recorded snapshot.</em></strong><br />Must run this test again<br />To create a new snapshot<br />And compare it to the previous one</p>
<p>Here is the saved snapshot:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650453606383/EJBYVsP6C.png" alt="image.png" /></p>
<hr />
<p>Creation of an helper function <code>makeSUT()</code><br />That will facilitate test setup<br />And also prevent any breaking changes:</p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeSUT</span><span class="hljs-params">()</span></span> -&gt; (sut: <span class="hljs-type">UIHostingController</span>&lt;<span class="hljs-type">StatisticsView</span>&gt;, viewModel: <span class="hljs-type">StatisticsViewModel</span>) {
    <span class="hljs-keyword">let</span> viewModel = <span class="hljs-type">StatisticsViewModel</span>()
    <span class="hljs-keyword">let</span> statisticsView = <span class="hljs-type">StatisticsView</span>(viewModel: viewModel)
    <span class="hljs-keyword">let</span> sut = <span class="hljs-type">UIHostingController</span>(rootView: statisticsView)
    <span class="hljs-keyword">return</span> (sut, viewModel)
  }
</code></pre>
<p>Creation of an <code>assertSnapshot()</code> function helper<br />Easy test setup<br />Improve test readability<br />Avoid repetitions</p>
<pre><code class="lang-swift"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">assertSnapshot</span><span class="hljs-params">(matching controller: UIHostingController&lt;StatisticsView&gt;, traits: UITraitCollection = .<span class="hljs-keyword">init</span><span class="hljs-params">(userInterfaceStyle: .light)</span></span></span>, testName: <span class="hljs-type">String</span>, file: <span class="hljs-type">StaticString</span> = #filePath, line: <span class="hljs-type">UInt</span> = #line) {
    <span class="hljs-type">SnapshotTesting</span>.assertSnapshot(matching: controller.rootView,
                                   <span class="hljs-keyword">as</span>: .image(drawHierarchyInKeyWindow: <span class="hljs-literal">true</span>,
                                              layout: .device(config: .iPhoneSe),
                                              traits: traits),
                                   named: <span class="hljs-string">"StatisticsView"</span>,
                                   file: file,
                                   testName: testName,
                                   line: line)
  }
</code></pre>
<p>Refactor the test like this:</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_lightMode</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT()

    assertSnapshot(matching: sut, testName: <span class="hljs-string">"LIGHT_MODE"</span>)
  }
</code></pre>
<hr />
<p>Creation of test for Dark mode</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_darkMode</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT()

    assertSnapshot(matching: sut,
                   traits: .<span class="hljs-keyword">init</span>(userInterfaceStyle: .dark),
                   testName: <span class="hljs-string">"DARK_MODE"</span>)
  }
</code></pre>
<p>Here is the saved snapshot:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650454815558/2qqiXejFq.png" alt="image.png" /></p>
<hr />
<p>Creation of test for dymamic type</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_dynamicType</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> (sut, <span class="hljs-number">_</span>) = makeSUT()

    assertSnapshot(matching: sut,
                   traits: .<span class="hljs-keyword">init</span>(preferredContentSizeCategory: .extraExtraExtraLarge),
                   testName: <span class="hljs-string">"EXTRA_EXTRA_EXTRA_LARGE"</span>)
  }
</code></pre>
<p>Here is the new snapshot:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650486684043/mv_ezXpJt.png" alt="image.png" /></p>
<hr />
<p>Now test the UI according to the user input<br />You cannot directly test a swiftUI view<br />But can change the view state via the view model<br />To verify that UI behaves correctly</p>
<pre><code class="lang-swift">  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_ascendingOrder</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> (sut, viewModel) = makeSUT()

    viewModel.toggleDescending()

    assertSnapshot(matching: sut,
                   testName: <span class="hljs-string">"ASCENDING_ORDER"</span>)
  }
</code></pre>
<p>Here is the new snapshot:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650455467648/eU_TNaFG1.png" alt="image.png" />
The arrow of the image is inverted<br />Transactions are in ascending order<br />Everything is good 😎</p>
<hr />
<p>Simulation of a regression<br />To see how to debug a test failure<br />Remove the "s" letter from the title "Statistics"<br />Run of all tests<br />They failed:<br /><strong><em>failed - Snapshot "StatisticsView" does not match reference</em></strong>.<br />In the build section<br />We can see where the problem comes from<br />The diff snapshot clearly tells you where the problem is<br />Here the letter "s" which has disappeared
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1650456307850/hF45bHH0i.png" alt="image.png" />
This diff snapshot helps a lot<br />Tell you precisely where the problem is<br />That avoid to waste time in debug<br />Increasing the value of those tests</p>
<hr />
<p>To conclude<br />These snapshots can be integrated into GIT<br />And these tests can be automated via CI/CD</p>
<p>I hope you enjoyed this test snapshots introduction<br />It is a very powerful tool<br />A must have it in your toolbox</p>
<p>That's it !!</p>
]]></content:encoded></item><item><title><![CDATA[SwiftUI - Integrate UI without a ready backend]]></title><description><![CDATA[Problem: How to integrate UI with a not ready backend? Solution: By decoupling the model returned by the API from the model that manages UI]]></description><link>https://swiftuicentral.com/swiftui-integrate-ui-without-a-ready-backend</link><guid isPermaLink="true">https://swiftuicentral.com/swiftui-integrate-ui-without-a-ready-backend</guid><category><![CDATA[Swift]]></category><category><![CDATA[iOS]]></category><category><![CDATA[UI]]></category><category><![CDATA[TDD (Test-driven development)]]></category><category><![CDATA[SwiftUI]]></category><dc:creator><![CDATA[Alexandre Alcuvilla]]></dc:creator><pubDate>Wed, 16 Feb 2022 20:23:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/12ZuBC65u98/upload/v1645042443669/BOVLwDKCp.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-problem-how-to-integrate-ui-with-a-not-ready-backend">Problem: How to integrate UI with a not ready backend?</h2>
<h3 id="heading-solution-by-decoupling-the-model-returned-by-the-api-from-the-model-that-manages-the-ui-display">Solution: By decoupling the model returned by the API from the model that manages the UI display !</h3>
<p>Simple example with this interface inspired by the Message app:<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643664264257/vBr0wPhPd.png" alt="image.png" /></p>
<p>The row that displays a message only needs data in <code>String</code> format and a <code>Bool</code> to know if there is a new message:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643664780351/44hINmMum.png" alt="image.png" /></p>
<p>Create the model <code>MessageUIModel</code> that meets this need:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessageUIModel</span>: <span class="hljs-title">Identifiable</span> </span>{
  <span class="hljs-keyword">let</span> id: <span class="hljs-type">Int</span>
  <span class="hljs-keyword">let</span> initials: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> title: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> message: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> date: <span class="hljs-type">String</span>
  <span class="hljs-keyword">let</span> isUnread: <span class="hljs-type">Bool</span>
}
</code></pre>
<p>Create the view model <code>MessagesViewModel</code> for this view with an array of <code>MessageUIModel</code> as a <code>@Published</code> property:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessagesViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  @<span class="hljs-type">Published</span> <span class="hljs-keyword">var</span> messages = [<span class="hljs-type">MessageUIModel</span>]()

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetch</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// Wait for backend to get data from API</span>
  }
}
</code></pre>
<p>Integration of the view model in the <code>MessagesView</code>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessagesView</span>: <span class="hljs-title">View</span> </span>{
  @<span class="hljs-type">StateObject</span> <span class="hljs-keyword">var</span> viewModel = <span class="hljs-type">MessagesViewModel</span>()

  <span class="hljs-keyword">var</span> body: some <span class="hljs-type">View</span> {
    <span class="hljs-type">Text</span>(<span class="hljs-string">"Hello World !!"</span>)
  }
}
</code></pre>
<p>Creation of fake data from the <code>MessageUIModel</code> model with hardcoded values and <code>MessagesViewModel</code> inheritance :</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockHardcodedMessagesViewModel</span>: <span class="hljs-title">MessagesViewModel</span> </span>{
  <span class="hljs-keyword">override</span> <span class="hljs-keyword">init</span>() {
    <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
    fetch()
  }

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetch</span><span class="hljs-params">()</span></span> {
    messages = [
      .<span class="hljs-keyword">init</span>(id: <span class="hljs-number">1</span>, initials: <span class="hljs-string">"AA"</span>, title: <span class="hljs-string">"Alexander Anderson"</span>, message: <span class="hljs-string">"Hello!! How are you?"</span>, date: <span class="hljs-string">"09:45 AM"</span>, isUnread: <span class="hljs-literal">true</span>),
      .<span class="hljs-keyword">init</span>(id: <span class="hljs-number">2</span>, initials: <span class="hljs-string">"J"</span>, title: <span class="hljs-string">"Jessica"</span>, message: <span class="hljs-string">"This a short message"</span>, date: <span class="hljs-string">"Yesterday"</span>, isUnread: <span class="hljs-literal">true</span>),
      .<span class="hljs-keyword">init</span>(id: <span class="hljs-number">3</span>, initials: <span class="hljs-string">"?"</span>, title: <span class="hljs-string">"+33 6 45 67 66 66"</span>, message: <span class="hljs-string">"Un message en français cool !!"</span>, date: <span class="hljs-string">"Tuesday"</span>, isUnread: <span class="hljs-literal">false</span>),
      .<span class="hljs-keyword">init</span>(id: <span class="hljs-number">4</span>, initials: <span class="hljs-string">"GP"</span>, title: <span class="hljs-string">"Georges Pitt"</span>, message: <span class="hljs-string">"This a very long message to test the line limit that must only displays 1 line, and not more this text must be troncated"</span>, date: <span class="hljs-string">"1/3/22"</span>, isUnread: <span class="hljs-literal">true</span>)
    ]
  }
}
</code></pre>
<p>We must now display this data in the live preview using the <code>MockHardcodedMessageViewModel</code> class:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessagesView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-type">MessagesView</span>(viewModel: <span class="hljs-type">MockHardcodedMessagesViewModel</span>())
      .preferredColorScheme(.dark)
  }
}
</code></pre>
<p>Creation of the <code>MessagesView</code> which allows to display these datas:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessagesView</span>: <span class="hljs-title">View</span> </span>{
  @<span class="hljs-type">StateObject</span> <span class="hljs-keyword">var</span> viewModel = <span class="hljs-type">MessagesViewModel</span>()

  <span class="hljs-keyword">var</span> body: some <span class="hljs-type">View</span> {
    <span class="hljs-type">NavigationView</span> {
      <span class="hljs-type">ScrollView</span> {
        <span class="hljs-type">LazyVStack</span> {
          <span class="hljs-type">ForEach</span>(viewModel.messages) { message <span class="hljs-keyword">in</span>
            <span class="hljs-type">HStack</span> {
              <span class="hljs-keyword">if</span> message.isUnread {
                <span class="hljs-type">Circle</span>()
                  .frame(width: <span class="hljs-number">10</span>, height: <span class="hljs-number">10</span>)
              } <span class="hljs-keyword">else</span> {
                <span class="hljs-type">Circle</span>()
                  .fill(.clear)
                  .frame(width: <span class="hljs-number">10</span>, height: <span class="hljs-number">10</span>)
              }
              <span class="hljs-type">Text</span>(message.initials)
                .font(.title2)
                .bold()
                .frame(width: <span class="hljs-number">50</span>, height: <span class="hljs-number">50</span>)
                .foregroundColor(.white)
                .background(.gray)
                .clipShape(<span class="hljs-type">Circle</span>())
              <span class="hljs-type">VStack</span>(alignment: .leading, spacing: <span class="hljs-number">6</span>) {
                <span class="hljs-type">HStack</span> {
                  <span class="hljs-type">Text</span>(message.title)
                    .font(.headline)
                  <span class="hljs-type">Spacer</span>()
                  <span class="hljs-type">Text</span>(message.date)
                    .font(.callout)
                    .foregroundColor(.secondary)
                }
                <span class="hljs-type">Text</span>(message.message)
                  .font(.body)
                  .foregroundColor(.secondary)
                  .lineLimit(<span class="hljs-number">1</span>)
              }
            }
          }
          .padding()
        }
      }
      .navigationTitle(<span class="hljs-string">"Messages"</span>)
    }
  }
}
</code></pre>
<p>You can visualize your fake datas in the live preview 😎:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643666388354/pQtWpMxpB.png" alt="image.png" /></p>
<p>Having created your UI, the back-end guys give you a payload of what the response <strong>JSON</strong> might look like:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"items"</span>: [
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">"Alexander"</span>,
      <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">"Anderson"</span>,
      <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Hello!! How are you?"</span>,
      <span class="hljs-attr">"phone_number"</span>: {
        <span class="hljs-attr">"international"</span>: <span class="hljs-string">"+33 6 56 67 45 66"</span>
      },
      <span class="hljs-attr">"update_date"</span>: <span class="hljs-string">"2022-01-31T08:45:33Z"</span>,
      <span class="hljs-attr">"unread_count"</span>: <span class="hljs-number">1</span>
    }
  ]
}
</code></pre>
<p>From this information create a fake <strong>JSON</strong> that will simulate a response from the backend, create a file of type empty and name it <strong>messages.json</strong>:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643552177558/HeIrtBxTe.png" alt=" image.png" /></p>
<p>Creation of the <strong>JSON</strong> that simulates a response from the API server with the datas used previously:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"items"</span>: [
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">"Alexander"</span>,
      <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">"Anderson"</span>,
      <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Hello!! How are you?"</span>,
      <span class="hljs-attr">"phone_number"</span>: {
        <span class="hljs-attr">"international"</span>: <span class="hljs-string">"+33 6 56 67 45 66"</span>
      },
      <span class="hljs-attr">"update_date"</span>: <span class="hljs-string">"2022-01-31T08:45:33Z"</span>,
      <span class="hljs-attr">"unread_count"</span>: <span class="hljs-number">1</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
      <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">"Jessica"</span>,
      <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">""</span>,
      <span class="hljs-attr">"message"</span>: <span class="hljs-string">"This a short message"</span>,
      <span class="hljs-attr">"phone_number"</span>: {
        <span class="hljs-attr">"international"</span>: <span class="hljs-string">"+33 6 45 67 66 66"</span>
      },
      <span class="hljs-attr">"update_date"</span>: <span class="hljs-string">"2022-01-30T17:54:37Z"</span>,
      <span class="hljs-attr">"unread_count"</span>: <span class="hljs-number">10</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
      <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">""</span>,
      <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">""</span>,
      <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Un message en français cool !!"</span>,
      <span class="hljs-attr">"phone_number"</span>: {
        <span class="hljs-attr">"international"</span>: <span class="hljs-string">"+33 6 45 67 99 66"</span>
      },
      <span class="hljs-attr">"update_date"</span>: <span class="hljs-string">"2022-01-25T17:12:33Z"</span>,
      <span class="hljs-attr">"unread_count"</span>: <span class="hljs-number">0</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
      <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">"Georges"</span>,
      <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">"Pitt"</span>,
      <span class="hljs-attr">"message"</span>: <span class="hljs-string">"This a very long message to test the line limit that must only displays 1 line"</span>,
      <span class="hljs-attr">"phone_number"</span>: {
        <span class="hljs-attr">"international"</span>: <span class="hljs-string">"+33 6 45 67 66 98"</span>
      },
      <span class="hljs-attr">"update_date"</span>: <span class="hljs-string">"2022-01-03T12:54:23Z"</span>,
      <span class="hljs-attr">"unread_count"</span>: <span class="hljs-number">1</span>
    }
  ]
}
</code></pre>
<p>Creation of a model that can parse this <strong>JSON</strong> with <code>Decodable</code>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Root</span></span>: Decodable {
  <span class="hljs-keyword">let</span> items: [Message]

  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Message</span></span>: Decodable {
    <span class="hljs-keyword">let</span> id: Int
    <span class="hljs-keyword">let</span> firstname: <span class="hljs-built_in">String</span>
    <span class="hljs-keyword">let</span> lastname: <span class="hljs-built_in">String</span>
    <span class="hljs-keyword">let</span> message: <span class="hljs-built_in">String</span>
    <span class="hljs-keyword">let</span> phoneNumber: PhoneNumber
    <span class="hljs-keyword">let</span> updateDate: Date
    <span class="hljs-keyword">let</span> unreadCount: Int

    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PhoneNumber</span></span>: Decodable {
      <span class="hljs-keyword">let</span> international: <span class="hljs-built_in">String</span>
    }
  }
}
</code></pre><p>Creating an <code>extension</code> on the <code>Bundle</code> type to make it easier to decode <strong>JSON</strong> from a file:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Bundle</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">decode</span>&lt;T: Decodable&gt;<span class="hljs-params">(<span class="hljs-number">_</span> type: T.<span class="hljs-keyword">Type</span>, from file: String)</span></span> -&gt; <span class="hljs-type">T</span> {
    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> url = <span class="hljs-keyword">self</span>.url(forResource: file, withExtension: <span class="hljs-literal">nil</span>) <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">fatalError</span>(<span class="hljs-string">"Failed to locate \(file) in bundle."</span>)
    }

    <span class="hljs-keyword">guard</span> <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">try</span>? <span class="hljs-type">Data</span>(contentsOf: url) <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">fatalError</span>(<span class="hljs-string">"Failed get data from url \(url)."</span>)
    }

    <span class="hljs-keyword">let</span> decoder = <span class="hljs-type">JSONDecoder</span>()
    decoder.dateDecodingStrategy = .iso8601
    decoder.keyDecodingStrategy = .convertFromSnakeCase

    <span class="hljs-keyword">do</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">try</span> decoder.decode(<span class="hljs-type">T</span>.<span class="hljs-keyword">self</span>, from: data)
    } <span class="hljs-keyword">catch</span> {
      <span class="hljs-built_in">fatalError</span>(<span class="hljs-string">"Failed to decode \(file) from bundle with error: \(error)"</span>)
    }
  }
}
</code></pre>
<p>Creating fake data from this <strong>JSON</strong> with the <code>MockApiMessagesViewModel</code> type:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockApiMessagesViewModel</span>: <span class="hljs-title">MessagesViewModel</span> </span>{
  <span class="hljs-keyword">override</span> <span class="hljs-keyword">init</span>() {
    <span class="hljs-keyword">super</span>.<span class="hljs-keyword">init</span>()
    fetch()
  }

  <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fetch</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> apiMessages = <span class="hljs-type">Bundle</span>.main.decode(<span class="hljs-type">Root</span>.<span class="hljs-keyword">self</span>, from: <span class="hljs-string">"messages.json"</span>).items

    messages = apiMessages.<span class="hljs-built_in">map</span> { apiMessage <span class="hljs-keyword">in</span>
      <span class="hljs-type">MessageUIModel</span>(
        id: apiMessage.id,
        initials: <span class="hljs-string">"AA"</span>,
        title: apiMessage.firstname,
        message: apiMessage.message,
        date: <span class="hljs-type">ISO8601DateFormatter</span>().string(from: apiMessage.updateDate),
        isUnread: <span class="hljs-literal">false</span>)
    }
  }
}
</code></pre>
<p>Use the fake data from the <code>MockApiMessageViewModel</code> class in the live preview:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessagesView_Previews</span>: <span class="hljs-title">PreviewProvider</span> </span>{
  <span class="hljs-keyword">static</span> <span class="hljs-keyword">var</span> previews: some <span class="hljs-type">View</span> {
    <span class="hljs-type">MessagesView</span>(viewModel: <span class="hljs-type">MockHardcodedMessagesViewModel</span>())
      .preferredColorScheme(.dark)
    <span class="hljs-type">MessagesView</span>(viewModel: <span class="hljs-type">MockApiMessagesViewModel</span>())
      .preferredColorScheme(.dark)
  }
}
</code></pre>
<p>The data displayed are not correctly formatted:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643667234721/uX2Ys7Ihg.png" alt="image.png" /></p>
<p>Start with the <code>initials</code> property which displays the initials of the first name and last name or ? if empty :</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessagesViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-comment">// MARK: - Helpers</span>

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">initials</span><span class="hljs-params">(<span class="hljs-keyword">for</span> message: Root.Message)</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">let</span> firstLetter = <span class="hljs-type">String</span>(message.firstname.<span class="hljs-keyword">prefix</span>(<span class="hljs-number">1</span>))
    <span class="hljs-keyword">let</span> secondLetter = <span class="hljs-type">String</span>(message.lastname.<span class="hljs-keyword">prefix</span>(<span class="hljs-number">1</span>))

    <span class="hljs-keyword">switch</span> (!firstLetter.isEmpty, !secondLetter.isEmpty) {
    <span class="hljs-keyword">case</span> (<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>):
      <span class="hljs-keyword">return</span> <span class="hljs-string">"\(firstLetter)\(secondLetter)"</span>
    <span class="hljs-keyword">case</span> (<span class="hljs-literal">true</span>, <span class="hljs-number">_</span>):
      <span class="hljs-keyword">return</span> firstLetter
    <span class="hljs-keyword">case</span> (<span class="hljs-number">_</span>, <span class="hljs-literal">true</span>):
      <span class="hljs-keyword">return</span> secondLetter
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"?"</span>
    }
  }
</code></pre>
<p>Use the function <code>initial(for:)</code> when creating the model <code>MessageUIModel</code>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockApiMessagesViewModel</span>: <span class="hljs-title">MessagesViewModel</span> </span>{
    ...
    messages = apiMessages.<span class="hljs-built_in">map</span> { apiMessage <span class="hljs-keyword">in</span>
      <span class="hljs-type">MessageUIModel</span>(
        id: apiMessage.id,
        initials: initials(<span class="hljs-keyword">for</span>: apiMessage),
        title: apiMessage.firstname,
        message: apiMessage.message,
        date: <span class="hljs-type">ISO8601DateFormatter</span>().string(from: apiMessage.updateDate),
        isUnread: <span class="hljs-literal">false</span>)
    }
  }
}
</code></pre>
<p>The initials are correctly formatted:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643667648301/-Aob2hbSs.png" alt="image.png" /></p>
<p>Do the same to correctly format name, date and manage the visibility of  unread message:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessagesViewModel</span>: <span class="hljs-title">ObservableObject</span> </span>{
  ...
  <span class="hljs-comment">// MARK: - Helpers</span>
  ...
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">isUnread</span><span class="hljs-params">(<span class="hljs-keyword">for</span> message: Root.Message)</span></span> -&gt; <span class="hljs-type">Bool</span> {
    message.unreadCount &gt; <span class="hljs-number">0</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">formattedDate</span><span class="hljs-params">(<span class="hljs-keyword">for</span> message: Root.Message )</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">let</span> formatter = <span class="hljs-type">DateFormatter</span>()
    <span class="hljs-keyword">let</span> isToday = <span class="hljs-type">Calendar</span>.current.isDateInToday(message.updateDate)
    <span class="hljs-keyword">let</span> isYesterday = <span class="hljs-type">Calendar</span>.current.isDateInYesterday(message.updateDate)

    <span class="hljs-keyword">let</span> now = <span class="hljs-type">Date</span>()
    <span class="hljs-keyword">let</span> oneWeekAgo = <span class="hljs-type">Calendar</span>.current.startOfDay(<span class="hljs-keyword">for</span>: now).addingTimeInterval(-<span class="hljs-number">604_800</span>)
    <span class="hljs-keyword">let</span> isLessThanOneWeekAgo = (oneWeekAgo...now).<span class="hljs-built_in">contains</span>(message.updateDate)

    <span class="hljs-keyword">if</span> isToday {
      formatter.timeStyle = .short
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> isYesterday {
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Yesterday"</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> isLessThanOneWeekAgo {
      formatter.dateFormat = <span class="hljs-string">"EEEE"</span>
      <span class="hljs-keyword">return</span> formatter.string(from: message.updateDate)
    } <span class="hljs-keyword">else</span> {
      formatter.timeStyle = .<span class="hljs-keyword">none</span>
      formatter.dateStyle = .short
    }

    <span class="hljs-keyword">return</span> formatter.string(from: message.updateDate)
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">title</span><span class="hljs-params">(<span class="hljs-keyword">for</span> message: Root.Message)</span></span> -&gt; <span class="hljs-type">String</span> {
    <span class="hljs-keyword">let</span> isFirstname = !message.firstname.isEmpty
    <span class="hljs-keyword">let</span> isLastname = !message.lastname.isEmpty

    <span class="hljs-keyword">switch</span> (isFirstname, isLastname) {
    <span class="hljs-keyword">case</span> (<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>):
      <span class="hljs-keyword">return</span> <span class="hljs-string">"\(message.firstname) \(message.lastname)"</span>
    <span class="hljs-keyword">case</span> (<span class="hljs-literal">true</span>, <span class="hljs-number">_</span>):
      <span class="hljs-keyword">return</span> message.firstname
    <span class="hljs-keyword">case</span> (<span class="hljs-number">_</span>, <span class="hljs-literal">true</span>):
      <span class="hljs-keyword">return</span> message.lastname
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> message.phoneNumber.international
    }
  }
}
</code></pre>
<p>Use <code>isUnread(for:)</code>, <code>formattedDate(for:)</code>, <code>title(for:)</code> when create the <code>MessageUIModel</code>:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockApiMessagesViewModel</span>: <span class="hljs-title">MessagesViewModel</span> </span>{
    ...
    messages = apiMessages.<span class="hljs-built_in">map</span> { apiMessage <span class="hljs-keyword">in</span>
      <span class="hljs-type">MessageUIModel</span>(
        id: apiMessage.id,
        initials: initials(<span class="hljs-keyword">for</span>: apiMessage),
        title: title(<span class="hljs-keyword">for</span>: apiMessage),
        message: apiMessage.message,
        date: formattedDate(<span class="hljs-keyword">for</span>: apiMessage),
        isUnread: isUnread(<span class="hljs-keyword">for</span>: apiMessage))
    }
  ...
}
</code></pre>
<p>Now your view is displayed correctly (you may need to change the dates in the <strong>JSON</strong> to have consistent dates to display <strong>today</strong>, <strong>yesterday</strong>, ...)
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1643667931460/nQh57LJb8.png" alt="image.png" /></p>
<p>You just have to wait for the backend team to finish the route to retrieve the real <strong>JSON</strong> via an API request.</p>
<p>You can continue to integrate the next UI screen. The backend will not stop you anymore.</p>
<p>That's it!!</p>
]]></content:encoded></item></channel></rss>