<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pavel Holec on Medium]]></title>
        <description><![CDATA[Stories by Pavel Holec on Medium]]></description>
        <link>https://medium.com/@pavel-holec?source=rss-f48de8ef38d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QKVyYkAI3I0JMsgFUU_OEg@2x.jpeg</url>
            <title>Stories by Pavel Holec on Medium</title>
            <link>https://medium.com/@pavel-holec?source=rss-f48de8ef38d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:03:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavel-holec/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI modular architecture]]></title>
            <link>https://medium.com/@pavel-holec/swiftui-modular-architecture-9bb1647b70b8?source=rss-f48de8ef38d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb1647b70b8</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Pavel Holec]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 15:52:08 GMT</pubDate>
            <atom:updated>2024-12-04T15:57:16.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Xcode feature package split into targets" src="https://cdn-images-1.medium.com/max/1024/1*l978eTYXAqvTihZadx-uTQ.png" /><figcaption>A feature package split into targets</figcaption></figure><h3>Modular SwiftUI architecture</h3><p>When we started introducing SwiftUI in <a href="https://www.kiwi.com/">Kiwi.com</a> app, we already had to maintain 100+ UIKit screens. As we tried to convert them into SwiftUI in-place, without any other architectural change, the Xcode would just crash when attempting to work with SwiftUI previews.</p><p>To provide developers with a <strong>stable and fast SwiftUI previews</strong> and remove the need of running the app after each code change, we needed to introduce an architecture that would <strong>force views to be lightweight</strong> and independent of non-UI code.</p><h4>Feature package modularization</h4><p>First, we structured our app around isolated <strong>feature SPM packages</strong>, on top of shared ones. It was a bit tricky in the first versions of SwiftUI and SPM, but after those technologies stabilized, it turned out to be a great timesaver.</p><p>Primary benefits of splitting features into packages for us were:</p><ol><li>The ability to <strong>open each feature package on its own</strong> (instead of the whole project or workflow). <br>This is faster not only technically (by Xcode only managing a single package, although it may add few GBs of derived data), but it also makes it easier for a developer to concentrate on the feature as the relevant search, navigation, tests and previews in Xcode are easier to find, without distractions of unrelated app code.</li><li>When a feature is removed from the app, almost all it takes is to drop the feature package folder, as this architecture <strong>forces developers to write code in a relevant package</strong> in the first place, making it less likely to require hunting for the code spread through the whole codebase.</li><li><strong>Faster and stable SwiftUI previews</strong>, without the need to build code that belongs to unrelated features.</li></ol><h4>Package target modularization</h4><p>Second, to improve on the last point even more, due to the number of screens and features we had, we have further <strong>split each feature package</strong> into following targets:</p><ol><li><strong><em>Foo</em></strong> target that only contains protocols, reusable constants and simple logic-free types (such as structs or enums that only carry information across ui-domain boundary) and other light-weight code. This target can be freely imported by other features as <strong>it is dirt-cheap to build</strong>.</li><li><strong><em>FooMocks</em></strong> target that contains mocks of types defined in the above target (or types of dependent sub-feature targets) for both unit tests and SwiftUI preview purposes of this and any dependent feature.</li><li><strong><em>FooViews</em></strong> target that contains screen and component definitions, UI resources (images, localization) and other UI-only, mostly internal, types. It can optionally contain internal ViewModels that extract some non-trivial logic out of views for testability purposes.<br>This target may only depend on shared UI code, or other non-implementation targets of other (sub)features. This way, the build hierarchy <strong>never touches code that is expensive to build</strong>.</li><li><strong><em>FooImplementation</em></strong> is the target that contains the most costly implementation of the feature, a code that would take the majority of the whole app build time. This target is thus only allowed to be <strong>linked from the main app target</strong>, in most cases to be used purely for dependency injection.</li><li><strong><em>FooTests</em></strong> target that contains unit tests for this feature or its interaction with its sub-features.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONlUNr_IjSpziTx0Ve-2jw.png" /><figcaption>A feature package structure, dependencies and preview</figcaption></figure><h4>Exported imports</h4><p>To simplify the imports of these granular targets at a call site, they are reexporting their dependencies. The call site then only needs to import the single relevant target:</p><pre>// FooMocks/Exported.swift<br>@_exported import Foo<br><br>// FooViews/Exported.swift<br>@_exported import Foo<br><br>// FooImplementation/Exported.swift<br>@_exported import FooViews<br><br>// Call site ----------------------<br><br>// BarViews/Screen.swift<br>import FooViews      // Along with reexported Foo<br>import SharedViews<br>...<br><br>// App.swift<br>import FooImplementation // Along with reexported Foo and FooViews<br>import BarImplementation // Along with reexported Bar and BarViews<br>...</pre><p>Using this approach, our <strong>build cycle got significantly reduced</strong>. A developer can interact with the feature using SwiftUI preview almost immediately, rather than spending minutes waiting for the typical whole-app build and simulator run, plus the manual navigation into the relevant feature.</p><h4>Package target definition example</h4><p>Following example shows the SPM definition of a feature <strong><em>ForceUpdate</em></strong> that encapsulates all code related to that feature (protocols, data, business logic, UI, tests):</p><pre>let package = Package(<br>    name: &quot;ForceUpdate&quot;,<br>    defaultLocalization: &quot;en&quot;,<br>    platforms: [.iOS(.v16)],<br>    products: [<br>        .library(name: &quot;ForceUpdate&quot;, targets: [&quot;ForceUpdate&quot;]),<br>        .library(name: &quot;ForceUpdateImplementation&quot;, targets: [&quot;ForceUpdateImplementation&quot;]),<br>        .library(name: &quot;ForceUpdateMocks&quot;, targets: [&quot;ForceUpdateMocks&quot;]),<br>        .library(name: &quot;ForceUpdateViews&quot;, targets: [&quot;ForceUpdateViews&quot;]),<br>    ],<br>    dependencies: [<br>        .package(path: &quot;../../../Network/Networking&quot;),<br>        // ...<br>        .package(path: &quot;../../../UI/SharedUI&quot;),<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;ForceUpdate&quot;,<br>            dependencies: [<br>                &quot;Shared&quot;,<br>            ]<br>        ),<br>        .target(<br>            name: &quot;ForceUpdateImplementation&quot;,<br>            dependencies: [<br>                &quot;Dates&quot;,<br>                &quot;ForceUpdateViews&quot;,<br>                &quot;Networking&quot;,<br>                &quot;Shared&quot;,<br>                &quot;SharedUI&quot;,<br>            ]<br>        ),<br>        .target(<br>            name: &quot;ForceUpdateMocks&quot;,<br>            dependencies: [<br>                &quot;ForceUpdate&quot;,<br>            ]<br>        ),<br>        .target(<br>            name: &quot;ForceUpdateViews&quot;,<br>            dependencies: [<br>                &quot;ForceUpdateMocks&quot;,<br>                &quot;Logging&quot;,<br>                &quot;SharedUI&quot;,<br>            ]<br>        ),<br>        .testTarget(<br>            name: &quot;ForceUpdateTests&quot;,<br>            dependencies: [<br>                &quot;ForceUpdateImplementation&quot;,<br>                .product(name: &quot;NetworkingMocks&quot;, package: &quot;Networking&quot;),<br>            ]<br>        ),<br>)</pre><p>In our case, the incremental build times after introducing any UI change are less than a second for the feature package versus around 5 seconds for the whole app. Does not seem a huge difference one time, but when iterating on a feature, these build times quickly add up.</p><p>As a result of the above architecture, developers can concentrate on the feature in isolation, with almost <strong>instant preview feedback loop</strong> and with less chances of introducing code conflicts with the rest of the app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb1647b70b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating SwiftUI snapshot tests with Swift macros]]></title>
            <link>https://medium.com/@pavel-holec/generating-swiftui-snapshot-tests-with-swift-macros-0f31b231925e?source=rss-f48de8ef38d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f31b231925e</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <dc:creator><![CDATA[Pavel Holec]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 14:26:48 GMT</pubDate>
            <atom:updated>2024-02-16T14:26:48.083Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describes how our <a href="https://www.kiwi.com/">Kiwi.com</a> iOS project uses swift macros to drive automatic snapshot tests generation in order to keep tests synced with SwiftUI previews and to get rid of a lot of maintenance-requiring boilerplate.</p><blockquote>Note: Xcode currently does not offer native support for snapshot testing. This can be remedied by using third party library, such as <a href="https://github.com/pointfreeco/swift-snapshot-testing">swift-snapshot-testing</a>. This library is being used in following code examples.</blockquote><h4><strong>Problem</strong></h4><p>SwiftUI preview and snapshot test code live in different targets and often in different packages, especially when dealing with modular architecture.</p><p>We would like to <strong>reuse our existing (mocked and manually crafted) SwiftUI previews</strong> directly as-is for snapshot testing purposes to avoid code duplication and have the snapshot test code <strong>automatically generated </strong>from SwiftUI preview definitions, possibly with added autogenerated dark mode, accessibility size or locale variants.</p><h4><strong>Our Solution</strong></h4><p>In our <a href="https://www.kiwi.com/">Kiwi.com</a> project, we are using the power of <strong>swift macros </strong>in order to expose our existing SwiftUI preview properties and use them to generate matching test code in the test target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miD7CoTljg3k95MAoeekqQ.png" /></figure><h3>Macros on SwiftUI previews side</h3><p>In order to specify what previews we want to include in snapshot testing, we will be decorating the SwiftUI previews code with macros.</p><blockquote>Note: It seems the new #Preview macro cannot be used for these purposes, as it generates randomly named previews. We need to reach for a specific type from our test code, so for this solution, we will need to stick to using PreviewProvider previews.</blockquote><p>On the SwiftUI previews side, we will be using two sets of macros:</p><ol><li>A single <strong>SnapshotPreviews </strong>attached <strong>member </strong>macro to mark the whole <strong>PreviewProvider</strong> struct to opt-in for snapshot testing.</li><li>A <strong>SnapshotTest </strong>attached <strong>peer</strong> macro to mark preview properties to opt-in for snapshot testing. Alternatively, if your project should include all properties in snapshot tests, a counterpart macro <strong>SnapshotIgnored</strong> can be used to opt-out the property from snapshot testing instead and include all others automatically.</li></ol><p>The role of above macros is to generate and insert the list(s) of view properties that we want to snapshot test into the <strong>PreviewProvider</strong> type. Those properties can be represented by a custom <strong>SnapshotPreview</strong> type that contains the view itself, plus any metadata we will need to access in tests. This will be later consumed by the test macro that will depend on the existence of this list.</p><p>The implementation of these macros will be based on project needs. For example, in our current project, we implemented the macro to generate two separate sets of properties:</p><ul><li><strong>snapshots</strong> (for automated testing purposes, only for screens, opt-in based)</li><li><strong>screenshots</strong> (for documentation-only purposes of both screens and components, opt-out based)</li></ul><p>By switching between relevant snapshot and screenshot test plans, only relevant preview list properties are used (both locally and on the CI). This makes it possible to regenerate screenshots for the whole app after a release for example, while only keeping a limited set of snapshot tests for testing purposes, while using the same set of macros and test code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMcoDppcZVF1w_pEP5JL2A.png" /><figcaption>The result of expanded SnapshotPreviews macro with two distinct property lists</figcaption></figure><h3>Macros on the test target side</h3><p>At the test side, we will use <strong>SnapshotTests</strong> attached member macro to generate test methods for provided list of <strong>PreviewProvider</strong> types, assuming they contain the generated lists of preview properties by preview macros described above. Because of current limitations of freestanding macros to generate global scope variables, we currently still need to manually specify these two parts:</p><ol><li>(Optional for modular project) Which <strong>feature package</strong> to import and test (represented by a test class)</li><li>All <strong>PreviewProvider</strong> types that we want to include in the test case</li></ol><p>Test test code that we need to manually create and maintain in the repository would look like this:</p><pre>@testable import FooFeatureViews<br><br>@SnapshotTests(<br>    FooScreenPreviews.self,<br>    BarComponentPreviews.self<br>)<br>class FooFeatureTests: SnapshotTestCase {}</pre><p>The <strong>SnapshotTests</strong> macro on test side expands the above code into generated snapshot test code for the FooFeature package and all its previews (with a test method generated for each preview), along with required snapshot variants (device sizing, size category, locale etc.) or potentially different sets of previews (snapshots / screenshots):</p><pre>@testable import FooFeatureViews<br><br>@SnapshotTests(<br>    FooScreenPreviews.self,<br>    BarComponentPreviews.self<br>)<br>class FooFeatureTests: SnapshotTestCase {}<br><br>  // Following code is generated by @SnapshotTests macro:<br><br>func testFooScreen() {<br>    if isScreenshotsRecording {<br>        for snapshot in FooScreenPreviews.screenshots {<br>            assert(snapshot.view, name: &quot;\(snapshot.name)-scheme-light&quot;)<br>            assert(snapshot.view.environment(\.colorScheme, .dark), name: &quot;\(snapshot.name)-scheme-dark&quot;)<br>            assert(snapshot.view.environment(\.sizeCategory, .accessibilityExtraLarge), name: &quot;\(snapshot.name)-size-xl&quot;)<br>        }<br>    } else {<br>        for snapshot in FooScreenPreviews.snapshots {<br>            assert(snapshot.view, name: &quot;\(snapshot.name)&quot;)<br>        }<br>    }<br>}<br><br>func testBarComponent() {<br>    if isScreenshotsRecording {<br>        for snapshot in BarComponentPreviews.screenshots {<br>            assert(snapshot.view, name: &quot;\(snapshot.name)-scheme-light&quot;)<br>            assert(snapshot.view.environment(\.colorScheme, .dark), name: &quot;\(snapshot.name)-scheme-dark&quot;)<br>            assert(snapshot.view.environment(\.sizeCategory, .accessibilityExtraLarge), name: &quot;\(snapshot.name)-size-xl&quot;)<br>        }<br>    } else {<br>        for snapshot in BarComponentPreviews.snapshots {<br>            assert(snapshot.view, name: &quot;\(snapshot.name)&quot;)<br>        }<br>    }<br>}<br></pre><p>These generated tests correctly show up in the test plan and are automatically regenerated whenever a developer adds or removes the <strong>SnapshotTest</strong> flag from a SwiftUI property. The only thing we need to keep maintaining manually is the list of all PreviewProvider preview types we want to snapshot test.</p><h3>Implementation example</h3><p>The implementation of above macros might vary a lot based on project needs, but for the inspiration and to have some starting point, below are our macro implementations.</p><h4>SwiftUI preview macros</h4><pre>// DECLARATION<br><br>/// Generates screenshot and snapshot lists inside this `PreviewProvider`.<br>///<br>/// All `View` properties are automatically added to the list of screenshots, unless opted out using<br>/// ``ScreenshotIgnored()``.<br>///<br>/// Use ``SnapshotTest()`` to additionally mark properties to be used as a snapshot test.<br>/// Both screenshot and snapshot lists are expected to be used by ``SnapshotTests(_:)`` macro.<br>@attached(member, names: named(screenshots), named(snapshots))<br>public macro SnapshotPreviews() = #externalMacro(module: &quot;MacrosImplementation&quot;, type: &quot;SnapshotPreviewsMacro&quot;)<br><br>/// Marks this preview property to be included in the list of snapshot tests for the<br>/// current `PreviewProvider` with attached ``SnapshotPreviews()`` attribute.<br>@attached(peer, names: overloaded)<br>public macro SnapshotTest() = #externalMacro(module: &quot;MacrosImplementation&quot;, type: &quot;SnapshotTestMacro&quot;)<br><br>/// Marks this preview property to be excluded from the list of screenshots<br>/// for the current `PreviewProvider` with attached ``SnapshotPreviews()`` attribute.<br>@attached(peer, names: overloaded)<br>public macro ScreenshotIgnored() = #externalMacro(module: &quot;MacrosImplementation&quot;, type: &quot;ScreenshotIgnoredMacro&quot;)</pre><pre>// IMPLEMENTATION<br><br>import SwiftSyntax<br>import SwiftSyntaxMacros<br>import SwiftSyntaxMacroExpansion<br>import SwiftUI<br><br>/// Extracted properties of a specific preview used for snapshots.<br>public struct SnapshotPreview {<br>    public let view: AnyView<br>    /// Whether the preview is a device (fullscreen) size <br>    /// (suitable for screen previews) or only a device-width size (suitable for screen content or components)<br>    public let isDeviceSize: Bool<br>    public let name: String<br><br>    public init(_ view: AnyView, isDeviceSize: Bool, name: String) {<br>        self.view = view<br>        self.isDeviceSize = isDeviceSize<br>        self.name = name<br>    }<br>}<br><br>public struct SnapshotTestMacro: PeerMacro {<br><br>    public static func expansion(<br>        of _: SwiftSyntax.AttributeSyntax,<br>        providingPeersOf declaration: some DeclSyntaxProtocol,<br>        in _: some SwiftSyntaxMacros.MacroExpansionContext<br>    ) throws -&gt; [SwiftSyntax.DeclSyntax] {<br>        guard let variableDeclaration = declaration.as(VariableDeclSyntax.self),<br>              variableDeclaration.bindingSpecifier.tokenKind == .keyword(.var),<br>              variableDeclaration.modifiers.map(\.name.tokenKind).contains(.keyword(.static))<br>        else {<br>            throw MacroExpansionErrorMessage(&quot;`SnapshotTest` can be only applied to static `View` property&quot;)<br>        }<br><br>        return []<br>    }<br>}<br><br>public struct ScreenshotIgnoredMacro: PeerMacro {<br><br>    public static func expansion(<br>        of _: SwiftSyntax.AttributeSyntax,<br>        providingPeersOf declaration: some DeclSyntaxProtocol,<br>        in _: some SwiftSyntaxMacros.MacroExpansionContext<br>    ) throws -&gt; [SwiftSyntax.DeclSyntax] {<br>        guard let variableDeclaration = declaration.as(VariableDeclSyntax.self),<br>              variableDeclaration.bindingSpecifier.tokenKind == .keyword(.var),<br>              variableDeclaration.modifiers.map(\.name.tokenKind).contains(.keyword(.static))<br>        else {<br>            throw MacroExpansionErrorMessage(&quot;`ScreenshotIgnored` can be only applied to static `View` property&quot;)<br>        }<br><br>        return []<br>    }<br>}<br><br>public struct SnapshotPreviewsMacro: MemberMacro {<br><br>    private typealias SnapshotDeclarations = (snapshots: [String], screenshots: [String])<br><br>    // Prevents misuse of number of snapshot tests per screen<br>    private static let snapshotTestLimit = 8<br><br>    public static func expansion(<br>        of _: AttributeSyntax,<br>        providingMembersOf declaration: some DeclGroupSyntax,<br>        in _: some MacroExpansionContext<br>    ) throws -&gt; [SwiftSyntax.DeclSyntax] {<br>        guard let structDeclaration = declaration.as(StructDeclSyntax.self),<br>              let inheritedTypes = structDeclaration.inheritanceClause?.inheritedTypes,<br>              inheritedTypes.map(\.type.trimmed.description).contains(where: { $0 == &quot;PreviewProvider&quot; })<br>        else {<br>            throw MacroExpansionErrorMessage(&quot;`SnapshotPreviews` can be only applied to a `PreviewProvider` struct&quot;)<br>        }<br><br>        let members = structDeclaration.memberBlock.members.compactMap { member in<br>            member.as(MemberBlockItemSyntax.self)?.decl.as(VariableDeclSyntax.self)<br>        }<br><br>        let previewName = structDeclaration.name.text<br>        let isScreenPreview = previewName.hasSuffix(&quot;ScreenPreviews&quot;)<br>        let (snapshots, screenshots) = try snapshotDeclarations(members: members, isScreenPreview: isScreenPreview)<br><br>        if isScreenPreview {<br>            switch snapshots.count {<br>                case 0:<br>                    throw MacroExpansionErrorMessage(&quot;Screen preview must specify a `@SnapshotTest` property&quot;)<br>                case snapshotTestLimit...:<br>                    throw MacroExpansionErrorMessage(<br>                        &quot;Preview can specify at most \(snapshotTestLimit) `@SnapshotTest` properties&quot;<br>                    )<br>                default:<br>                    break<br>            }<br>        }<br><br>        return [<br>            &quot;&quot;&quot;<br>            static var snapshots: [SnapshotPreview] {<br>                [<br>                    \(raw: snapshots.joined(separator: &quot;,\n&quot;))<br>                ]<br>            }<br>            &quot;&quot;&quot;,<br>            &quot;&quot;&quot;<br>            static var screenshots: [SnapshotPreview] {<br>                [<br>                    \(raw: screenshots.joined(separator: &quot;,\n&quot;))<br>                ]<br>            }<br>            &quot;&quot;&quot;,<br>        ]<br>    }<br><br>    private static func snapshotDeclarations(<br>        members: [VariableDeclSyntax],<br>        isScreenPreview: Bool<br>    ) throws -&gt; SnapshotDeclarations {<br><br>        var snapshots = [String]()<br>        var screenshots = [String]()<br>        var isolatedScreenshot = &quot;&quot;<br>        var isGlobalIntrinsicSize = false<br><br>        for member in members {<br><br>            guard let binding = member.bindings.first,<br>                  let memberName = binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text,<br>                  binding.typeAnnotation?.type.as(SomeOrAnyTypeSyntax.self)?.trimmedDescription == &quot;some View&quot;<br>            else {<br>                continue<br>            }<br><br>            guard let accessorBlock = member.bindings.first?.accessorBlock,<br>                  let codeBlocks = accessorBlock.accessors.as(CodeBlockItemListSyntax.self)<br>            else {<br>                throw MacroExpansionErrorMessage(&quot;\(member) is empty&quot;)<br>            }<br><br>            if memberName == &quot;previews&quot; {<br>                isGlobalIntrinsicSize = containsIntrinsicSizePreviewLayout(codeBlocks)<br>            }<br><br>            let isDeviceSize = (isGlobalIntrinsicSize || containsIntrinsicSizePreviewLayout(codeBlocks)) == false<br>            let declaration = &quot;&quot;&quot;<br>            SnapshotPreview(AnyView(\(memberName)), isDeviceSize: \(isDeviceSize), name: &quot;\(memberName)&quot;)<br>            &quot;&quot;&quot;<br><br>            let attributeNames = member.attributes.as(AttributeListSyntax.self)?.compactMap { attribute in<br>                attribute.as(AttributeSyntax.self)?.attributeName.as(IdentifierTypeSyntax.self)?.name.text<br>            } ?? []<br><br>            if attributeNames.contains(&quot;SnapshotTest&quot;) {<br>                if isScreenPreview == false {<br>                    throw MacroExpansionErrorMessage(&quot;Only screen previews can contain `@SnapshotTest` properties&quot;)<br>                }<br><br>                snapshots.append(declaration)<br>            }<br><br>            if attributeNames.contains(&quot;ScreenshotIgnored&quot;) == false {<br>                if memberName == &quot;previews&quot; {<br>                    isolatedScreenshot = declaration<br>                } else {<br>                    screenshots.append(declaration)<br>                }<br>            }<br>        }<br><br>        if screenshots.isEmpty, isolatedScreenshot.isEmpty == false {<br>            screenshots.append(isolatedScreenshot)<br>        }<br><br>        return SnapshotDeclarations(snapshots: snapshots, screenshots: screenshots)<br>    }<br><br>    private static func containsIntrinsicSizePreviewLayout(_ codeBlocks: CodeBlockItemListSyntax) -&gt; Bool {<br>        codeBlocks<br>            .compactMap { $0.item.as(FunctionCallExprSyntax.self) }<br>            .contains(where: previewLayoutIsIntrinsicSize)<br>    }<br><br>    // Recursively detect whether the view property uses `previewLayout` with intrinsic layout.<br>    private static func previewLayoutIsIntrinsicSize(syntax: FunctionCallExprSyntax) -&gt; Bool {<br>        guard let calledExpression = syntax.calledExpression.as(MemberAccessExprSyntax.self) else {<br>            return false<br>        }<br><br>        if calledExpression.declName.trimmedDescription == &quot;previewLayout&quot; {<br>            let value = syntax.arguments.first?.expression.description ?? &quot;&quot;<br>            // The `screenContent` is our custom preview layout that bypasses the ScrollView scrollability<br>            return [&quot;.screenContent&quot;, &quot;.sizeThatFits&quot;].contains(value)<br>        } else {<br>            if let base = calledExpression.base?.as(FunctionCallExprSyntax.self) {<br>                return previewLayoutIsIntrinsicSize(syntax: base)<br>            }<br>        }<br><br>        return false<br>    }<br>}</pre><h4>Test target SnapshotTests macro</h4><pre>// DECLARATION<br><br>/// Adds tests for provided `PreviewProvider` types based on their snapshot and screenshot properties<br>/// that are generated by ``SnapshotPreviews()`` macro.<br>///<br>/// Typically, all Previews from a feature package should be listed<br>/// as parameters in a single test class that uses this attribute.<br>@attached(member, names: arbitrary)<br>public macro SnapshotTests(_ previews: any PreviewProvider.Type ...) = #externalMacro(module: &quot;MacrosImplementation&quot;, type: &quot;SnapshotTestsMacro&quot;)</pre><pre>// IMPLEMENTATION<br><br>import SwiftSyntaxMacros<br>import SwiftSyntax<br>import SwiftSyntaxMacroExpansion<br><br>public struct SnapshotTestsMacro: MemberMacro {<br><br>    public static func expansion(<br>        of node: SwiftSyntax.AttributeSyntax,<br>        providingMembersOf declaration: some DeclGroupSyntax,<br>        in _: some SwiftSyntaxMacros.MacroExpansionContext<br>    ) throws -&gt; [SwiftSyntax.DeclSyntax] {<br>        guard let classDecl = declaration.as(ClassDeclSyntax.self),<br>              classDecl.inheritanceClause?.inheritedTypes.trimmedDescription == &quot;SnapshotTestCase&quot;<br>        else {<br>            throw MacroExpansionErrorMessage(&quot;`SnapshotTests` can be only applied to subclass of `SnapshotTestCase`&quot;)<br>        }<br><br>        guard let arguments = node.arguments?.as(LabeledExprListSyntax.self) else {<br>            throw MacroExpansionErrorMessage(&quot;`SnapshotTests` has no preview arguments&quot;)<br>        }<br><br>        let previewExressions = arguments.map(\.expression).compactMap { expression in<br>            expression.as(MemberAccessExprSyntax.self)<br>        }<br><br>        let previews = previewExressions.compactMap(\.base?.trimmedDescription)<br><br>        return previews.map { preview in<br>            let previewName = preview.replacingOccurrences(of: &quot;Previews&quot;, with: &quot;&quot;)<br>            let assertPrefix = &quot;assert(snapshot.view&quot;<br>            let assertBase =<br>                &quot;, size: snapshot.isDeviceSize ? .device : .deviceWidth, name: \&quot;\\(snapshot.name)&quot;<br>            let assertSuffix = &quot;\&quot;)&quot;<br><br>            return<br>                &quot;&quot;&quot;<br>                func test\(raw: previewName)() {<br>                    if isScreenshotsRecording {<br>                        for snapshot in \(raw: preview).screenshots {<br>                            \(raw: assertPrefix)\(raw: assertBase)-scheme-light\(raw: assertSuffix)<br>                            \(raw: assertPrefix).environment(\\.colorScheme, .dark)\(raw: assertBase)-scheme-dark\(<br>                                raw: assertSuffix<br>                            )<br>                            \(raw: assertPrefix).environment(\\.sizeCategory, .accessibilityExtraLarge)\(<br>                                raw: assertBase<br>                            )-size-xl\(raw: assertSuffix)<br>                        }<br>                    } else {<br>                        for snapshot in \(raw: preview).snapshots {<br>                            \(raw: assertPrefix)\(raw: assertBase)\(raw: assertSuffix)<br>                        }<br>                    }<br>                }<br>                &quot;&quot;&quot;<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f31b231925e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ObservableObject initialisation from Environment]]></title>
            <link>https://medium.com/code-kiwi-com/observableobject-initialisation-from-environment-2efa054de06d?source=rss-f48de8ef38d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2efa054de06d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Pavel Holec]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 11:55:40 GMT</pubDate>
            <atom:updated>2023-10-09T15:39:20.730Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>ObservableObject initialization using Environment</strong></h3><p>At <a href="https://www.kiwi.com/en/">Kiwi.com</a>, the conversion of architecture from UIKit to pure SwiftUI was not without hiccups. One of them was finding a way to properly initialize an <strong>ObservableObject</strong> that depends on the environment that is injected from above.</p><p>For the purpose of this article, our <strong>ObservableObjects</strong> represent optional testable and mockable view models that drive the domain logic for some of the more complicated screens or flows in our app.</p><p>A side note on the SwiftUI environment for following code examples: As our app is driven by feature-based modular architecture, we are using <strong>Environment</strong> instead of <strong>EnvironmentObjects </strong>for our modular dependencies. This approach has some disadvantages (for example not being able to fully use <strong>@Published</strong> properties), but in our case, the modularity aspect overweights these limitations.</p><h3>Using environment to initialize state objects</h3><h4>Problem</h4><p>We want an <strong>ObservableObject</strong> (or any state or state object in general) to be initialized using an injected environment. The following naive attempts <em>(1)</em> and <em>(2)</em> do not compile, because the environment is not yet available during View initialization:</p><pre>struct SomeScreen: View {<br>  // Injected dependency<br>  @Environment(\.fooService) var fooService<br>  <br>  // Attempt 1)<br>  // Environment is not available yet ¯\_(ツ)_/¯<br>  @StateObject var viewModel = ViewModel(fooService: fooService)<br><br>  init() {<br>    // Attempt 2)<br>    // Neither is the environment available here<br>    _viewModel = .init(wrappedValue: .init(fooService: fooService))<br>  }<br>}</pre><p>There are workarounds to mitigate this inconvenience, such as setting the <strong>StateObject</strong> to a working state inside the <strong>onAppear()</strong> or <strong>task()</strong> block, but it seems each of these workarounds has some other disadvantage.</p><p>By trying out those workarounds, together with my colleagues <a href="https://medium.com/u/d8aef3d4b3ad">Šimon Javora</a> and <a href="https://medium.com/u/8844a454fa4d">Aliaksandr Baranouski</a>, we came up with a pattern that seems scalable enough.</p><h4>Solution</h4><p>For an <strong>ObservableObject</strong> that needs access to environment, <strong>the crux is to initiate such object <em>(2)</em> using the environment passed through the view init parameters <em>(1)</em></strong>, instead of using the actual <strong>@Environment(Object)</strong> <strong><em>(3)</em></strong> from within the view<strong>:</strong></p><pre>struct ParentScreen: View {<br>  @Environment(\.fooService) var fooService<br>  <br>  var body: some View {<br>    content<br>      .sheet(...) {<br>        ChildScreen(<br>          // 1) Here we DO have access to environment<br>          fooService: fooService<br>        )<br>      }<br>  }<br>}<br><br>struct ChildScreen: View {<br>  // 3) @Environment(\.fooService) var fooService<br>  @StateObject var viewModel: ViewModel<br><br>  init(fooService: FooService) {<br>    // 2) The ObservableObject initialisation is encapsulated here<br>    self._viewModel = .init(<br>      // 4) the autoclosure initializer needs to be used<br>      wrappedValue: .init(fooService: fooService)<br>    )<br>  }<br>}</pre><p>Please note the <strong>init(wrappedValue:)</strong> <strong>(4)</strong> is being used for the <strong>StateObject</strong> initialisation. It is a technical detail, but an important one. Without this initialiser (which uses <strong>@autoclosure</strong> to control a single initialisation and assignment), almost all other ways would result in the <strong>ObservableObject</strong> possibly being re-initiated many times during the same screen lifecycle (and sometimes not even being reassigned on 2nd and following run); which is almost never intended.</p><p>Preview and snapshot code is using the very same syntax. Both the whole navigation flow or an isolated screen behaves just like in the actual app, the only difference being the usage of mocked environment dependencies.</p><pre>struct ChildScreenPreviews: PreviewProvider {<br><br>  static var previews: some View {<br>    ChildScreen(fooService: .mock)<br>  }<br>}</pre><h3>A step further</h3><p>Passing the environment via View initializer also matches the technique Apple recommends in the <a href="https://developer.apple.com/documentation/swiftui/stateobject#Initialize-state-objects-using-external-data">documentation</a> for initialization of state objects using external data, although it does not specifically mention using environment as one of the options.</p><p>There is a small disadvantage with the current approach. The environment dependency is not encapsulated in the relevant view anymore, but it needs to be moved up to all call sites of that view, no matter whether the required environment is also relevant to them or not. We will now mitigate that with one additional technique.</p><h4>Passing the environment in a single parameter</h4><p>A technique my colleague <a href="https://medium.com/u/d8aef3d4b3ad">Šimon Javora</a> found is that the whole environment container can be obtained as a single property that includes all environment keys and objects.</p><pre>// Get the whole enviroment<br>@Environment(\.self) var environment</pre><p>This single property can be queried, but it can even be reapplied to any view. This can be helpful for example when passing the environment from <strong>UIViewControllerRepresentable</strong> back to SwiftUI view, as otherwise we would need to reapply all values and objects manually one by one.</p><pre>view<br>  // Reapply the whole enviroment<br>  .environment(\.self, environment)</pre><p>We will use this technique to improve the encapsulation of relevant environment values, so that the only environment the parent view needs to care about is that single environment container. This whole container is then passed to the child view initializer, possibly all the way down to the <strong>ObservableObject </strong>initializer.</p><pre>struct ParentScreen: View {<br>  // All the parent view needs to define is this property<br>  @Environment(\.self) var environment<br><br>  var body: some View {<br>    content<br>      .sheet(...) {<br>        ChildScreen(<br>          // We pass the whole environment as a single item<br>          environment: environment<br>        )<br>      }<br>  }<br>}<br><br>struct ChildScreen: View {<br>  @StateObject var viewModel: ViewModel<br><br>  init(environment: EnvironmentValues) {<br>    self._viewModel = .init(<br>      // The environment is passed to ObservableObject.<br>      // Alternatively, specific values can be extracted and passed further.<br>      wrappedValue: .init(environment: environment)<br>    )<br>  }<br>}</pre><h4>Bonus</h4><p>For snapshots that need to capture the screen state after an asynchronous action that is difficult to mock purely by injected environment, <strong>ObservableObject</strong> can be also prepared with overridden, hardcoded, properties.</p><p>For such cases, an additional <strong>fileprivate</strong> <strong>init</strong> allows <strong>ObservableObject </strong>to be injected in place of the StateObject directly.</p><pre>struct ChildScreen: View {<br><br>  @StateObject var viewModel: ViewModel<br><br>  // Regular init that constructs a VM from environment (or other data)<br>  init(environment: EnvironmentValues) {<br>    self._viewModel: .init(wrappedValue: .init(environment: environment))<br>  }<br><br>  // An optional init for mocked ObservableObject instances<br>  fileprivate init(viewModel: ViewModel) {<br>    self._viewModel = .init(wrappedValue: viewModel)<br>  }<br>}<br><br>struct ChildScreenPreviews: PreviewProvider {<br><br>  static var previews: some View {<br>    ChildScreen(<br>      // A mocked VM is used directly<br>      viewModel: .mock<br>        // Optionally hardcoding properties to specific state <br>        .mock(\.state, to: .loading)<br>    )<br>  }<br>}</pre><p>Now it should be one less trouble on a path to convert your codebase to pure SwiftUI. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2efa054de06d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/code-kiwi-com/observableobject-initialisation-from-environment-2efa054de06d">ObservableObject initialisation from Environment</a> was originally published in <a href="https://medium.com/code-kiwi-com">code.kiwi.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>