<?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 Ihor Vovk on Medium]]></title>
        <description><![CDATA[Stories by Ihor Vovk on Medium]]></description>
        <link>https://medium.com/@ihorvovk?source=rss-b1e4ac98d79a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VC8NeM1MIN599EuF</url>
            <title>Stories by Ihor Vovk on Medium</title>
            <link>https://medium.com/@ihorvovk?source=rss-b1e4ac98d79a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:37:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ihorvovk/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[Routing in SwiftUI With NavigationStack]]></title>
            <link>https://medium.com/better-programming/routing-in-swiftui-with-navigationstack-aa8bb9b032de?source=rss-b1e4ac98d79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa8bb9b032de</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ihor Vovk]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 14:31:14 GMT</pubDate>
            <atom:updated>2023-03-20T14:31:14.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>using only one router per a navigation layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xyGwDmxr123uepYP" /><figcaption>Photo by <a href="https://unsplash.com/de/@matthaeus123?utm_source=medium&amp;utm_medium=referral">matthaeus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This solution is an evolution of the routing approach with type-erased modifiers described in my article <a href="https://medium.com/better-programming/routing-in-swiftui-1dc87b7a47c7">Routing in SwiftUI</a>. Now it uses the new NavigationStack functionality available from iOS 16.0.</p><p>In that approach, the routing mechanism consisted of two components:</p><ul><li>Router subclass that defined navigation state and available navigation actions</li><li>View modifiers sheet, navigation, fullScreenCover that translated router state to actual SwiftUI navigation</li></ul><p>And we had to create a separate router instance for every view that performed navigation.</p><p>The new approach has a similar Router class implementation. But the translation of router state to SwiftUI navigation is different. We will use RoutingView instead of modifiers now. And we will need only one pair of Router + RoutingView per navigation layer.</p><p>Here, a navigation layer is either all views from a single NavigationStack, or just one view, if it does not participate in push navigation. If we present a sheet or a full-screen cover, it will be a new navigation layer with its own router and a navigation stack.</p><p>A known issue with the previous approach was that it did not allow us to navigate more than one view back with a single atomic animation. With NavigationStack, it is not an issue anymore.</p><h3>Implementation</h3><h4>Router state</h4><p>In the previous approach, we stored destination views as type erased AnyView in the router state. But we cannot store AnyView instances in NavigationStack path because the latter requires conformance to the Hashable protocol. Instead, we can introduce a specific model type to identify destination views — ViewSpec. The router state will look this way:</p><pre>struct State {<br>    var navigationPath: [ViewSpec] = []<br>    var presentingSheet: ViewSpec? = nil<br>    var presentingFullScreen: ViewSpec? = nil<br>    var presentingModal: ViewSpec? = nil<br>    var isPresented: Binding&lt;ViewSpec?&gt;<br>        <br>    var isPresenting: Bool {<br>        presentingSheet != nil || presentingFullScreen != nil || presentingModal != nil<br>    }<br>}</pre><p>Here, navigationPath represents push navigation over a stack view, presentingSheet — presenting a system sheet, presentingFullScreen — a system full-screen cover, presentingModal — a custom modal view.</p><p>isPresented is binding to either presentingSheet or presentingFullScreen state of the parent router. Router uses this binding to dismiss the corresponding navigation layer.</p><h4>ViewSpec</h4><p>ViewSpec is an enum that identifies a view.</p><p>This enum should contain all possible views we can present in our application. It can be flat, or it can include nested enums.</p><p>We can also specify the parameters required for the corresponding view creation.</p><p>Here is a simple flat enum for our sample app:</p><pre>enum ViewSpec: Equatable, Hashable {<br>    <br>    case main<br>    case list<br>    case detail(String)<br>    case alert<br>}<br><br>extension ViewSpec: Identifiable {<br>    <br>    var id: Self { self }<br>}</pre><h4>RoutingView</h4><p>RoutingView listens to changes in the corresponding router state and performs actual navigation.</p><p>It delegates the creation of a destination view to the router by passing two parameters: ViewSpec and Route — a type of navigation.</p><pre>struct RoutingView&lt;Content: View&gt;: View {<br>    <br>    @StateObject var router: Router<br>    private let content: Content<br>    <br>    init(router: Router, @ViewBuilder content: @escaping () -&gt; Content) {<br>        _router = StateObject(wrappedValue: router)<br>        self.content = content()<br>    }<br>    <br>    var body: some View {<br>        NavigationStack(path: router.navigationPath) {<br>            content<br>                .navigationDestination(for: ViewSpec.self) { spec in<br>                    router.view(spec: spec, route: .navigation)<br>                }<br>        }.sheet(item: router.presentingSheet) { spec in<br>            router.view(spec: spec, route: .sheet)<br>        }.fullScreenCover(item: router.presentingFullScreen) { spec in<br>            router.view(spec: spec, route: .fullScreenCover)<br>        }.modal(item: router.presentingModal) { spec in<br>            router.view(spec: spec, route: .modal)<br>        }<br>    }<br>}<br><br>enum Route {<br>    case navigation<br>    case sheet<br>    case fullScreenCover<br>    case modal<br>}</pre><p>RoutingView is a NavigationStack that can also present a sheet, fullScreenCover, and custom types of modal views. RoutingView should reside in the root of a navigation layer.</p><p>In the implementation of RoutingView we use bindings to the router state.</p><p>Let’s define them in Router extension:</p><pre>extension Router {<br>    <br>    var navigationPath: Binding&lt;[ViewSpec]&gt; {<br>        binding(keyPath: \.navigationPath)<br>    }<br>    <br>    var presentingSheet: Binding&lt;ViewSpec?&gt; {<br>        binding(keyPath: \.presentingSheet)<br>    }<br>    <br>    var presentingFullScreen: Binding&lt;ViewSpec?&gt; {<br>        binding(keyPath: \.presentingFullScreen)<br>    }<br>    <br>    var presentingModal: Binding&lt;ViewSpec?&gt; {<br>        binding(keyPath: \.presentingModal)<br>    }<br>    <br>    var isPresented: Binding&lt;ViewSpec?&gt; {<br>        state.isPresented<br>    }<br>}<br><br>private extension Router {<br>    <br>    func binding&lt;T&gt;(keyPath: WritableKeyPath&lt;State, T&gt;) -&gt; Binding&lt;T&gt; {<br>        Binding(<br>            get: { self.state[keyPath: keyPath] },<br>            set: { self.state[keyPath: keyPath] = $0 }<br>        )<br>    }<br>}</pre><h4>Custom modal presentation</h4><p>modal is an example of a custom modal view. We can use it for presenting custom alerts or simple dialogues.</p><p>Implemented as a function on View, it has a similar interface to sheet and fullScreenCover:</p><pre>extension View {<br>    <br>    func modal&lt;Item, Content&gt;(item: Binding&lt;Item?&gt;, onDismiss: (() -&gt; Void)? = nil, content: @escaping (Item) -&gt; Content) -&gt; some View where Item: Identifiable, Content: View {<br>        ZStack(alignment: .center) {<br>            self<br>            if let wrappedItem = item.wrappedValue {<br>                Color.black.opacity(0.5)<br>                    .ignoresSafeArea()<br>                VStack(spacing: 0) {<br>                    HStack {<br>                        Button {<br>                            item.wrappedValue = nil<br>                        } label: {<br>                            Image(systemName: &quot;xmark.circle&quot;)<br>                        }<br>                        <br>                        Spacer()<br>                    }.frame(height: 50)<br>                    .padding(.horizontal, 12)<br>                    <br>                    Divider()<br>                    content(wrappedItem)<br>                }.clipShape(RoundedRectangle(cornerRadius: 8))<br>                .background(<br>                    RoundedRectangle(cornerRadius: 8)<br>                        .foregroundColor(.white)<br>                ).padding(.horizontal, 16)<br>            }<br>        }<br>    }<br>}</pre><h4>Base Router navigation interface</h4><p>The base Router class provides navigation commands that can be called from more specific functions of subclasses or directly from views.</p><p>Those commands modify the router state resulting in actual navigation performed by the corresponding RoutingView.</p><pre>extension Router {<br>    <br>    func navigateTo(_ viewSpec: ViewSpec) {<br>        state.navigationPath.append(viewSpec)<br>    }<br>    <br>    func navigateBack() {<br>        state.navigationPath.removeLast()<br>    }<br>    <br>    func replaceNavigationStack(path: [ViewSpec]) {<br>        state.navigationPath = path<br>    }<br>    <br>    func presentSheet(_ viewSpec: ViewSpec) {<br>        state.presentingSheet = viewSpec<br>    }<br>    <br>    func presentFullScreen(_ viewSpec: ViewSpec) {<br>        state.presentingFullScreen = viewSpec<br>    }<br>    <br>    func presentModal(_ viewSpec: ViewSpec) {<br>        state.presentingModal = viewSpec<br>    }<br>    <br>    func dismiss() {<br>        if state.presentingSheet != nil {<br>            state.presentingSheet = nil<br>        } else if state.presentingFullScreen != nil {<br>            state.presentingFullScreen = nil<br>        } else if state.presentingModal != nil {<br>            state.presentingModal = nil<br>        } else if navigationPath.count &gt; 1 {<br>            state.navigationPath.removeLast()<br>        } else {<br>            state.isPresented.wrappedValue = nil<br>        }<br>    }<br>}</pre><h4>MainRouter</h4><p>Let’s consider a specific MainRouter subclass. It provides three methods for presenting other screens.</p><p>These methods encapsulate the actual type of presentation: as a sheet, full-screen cover, push navigation, etc.</p><pre>class MainRouter: Router {<br>    <br>    func presentList() {<br>        presentSheet(.list)<br>    }<br>    <br>    func presentDetail(description: String) {<br>        navigateTo(.detail(description))<br>    }<br>    <br>    func presentAlert() {<br>        presentModal(.alert)<br>    }<br>    <br>    override func view(spec: ViewSpec, route: Route) -&gt; AnyView {<br>        AnyView(buildView(spec: spec, route: route))<br>    }<br>}</pre><p>For convenience, the view factory method calls a @ViewBuilder function inside. It allows us to avoid many return calls and erase the resulting view type to AnyView only once.</p><pre>private extension MainRouter {<br>    <br>    @ViewBuilder<br>    func buildView(spec: ViewSpec, route: Route) -&gt; some View {<br>        switch spec {<br>        case .list:<br>            ListView(router: router(route: route))<br>        case .detail(let description):<br>            DetailView(description: description, router: router(route: route))<br>        case .alert:<br>            AlertView()<br>        default:<br>            EmptyView()<br>        }<br>    }<br>            <br>    func router(route: Route) -&gt; MainRouter {<br>        switch route {<br>        case .navigation:<br>            return self<br>        case .sheet:<br>            return MainRouter(isPresented: presentingSheet)<br>        case .fullScreenCover:<br>            return MainRouter(isPresented: presentingFullScreen)<br>        case .modal:<br>            return self<br>        }<br>    }<br>}</pre><h4>MainView</h4><p>MainView is the first view presented by our app. So, we wrap its content in RoutingView to allow navigation from it to other views.</p><pre>struct MainView: View {<br>    <br>    @StateObject private var router: MainRouter<br>    <br>    init(router: MainRouter) {<br>        _router = StateObject(wrappedValue: router)<br>    }<br>    <br>    var body: some View {<br>        RoutingView(router: router) {<br>            VStack {<br>                Spacer()<br>                Button(&quot;Present List&quot;) {<br>                    router.presentList()<br>                }<br>                <br>                Spacer()<br>            }<br>        }<br>    }<br>}</pre><p>Here is how we create and pass MainRouter to MainView, initialising the app:</p><pre>@main<br>struct RouterWithNavigationStackApp: App {<br>    <br>    @StateObject private var router = MainRouter(isPresented: .constant(.main))<br>    <br>    var body: some Scene {<br>        <br>        WindowGroup {<br>            MainView(router: router)<br>        }<br>    }<br>}</pre><h4>ListView</h4><p>ListView is intended to be presented modally as a sheet/fullScreenCover and supports push navigation.</p><p>So, we also wrap its content in RoutingView. Every view presented modally as sheet or fullScreenCover becomes the root view of a new navigation layer and should be wrapped in RoutingView to enable navigation in this layer.</p><p>Unless it does not support push navigation itself.</p><pre>struct ListView: View {<br>    <br>    @StateObject private var router: MainRouter<br>    <br>    init(router: MainRouter) {<br>        _router = StateObject(wrappedValue: router)<br>    }<br>    <br>    var body: some View {<br>        RoutingView(router: router) {<br>            VStack(spacing: 20) {<br>                ForEach(1..&lt;4) {<br>                    cell(index: $0)<br>                }<br>            }.toolbar {<br>                ToolbarItem(placement: .navigationBarLeading) {<br>                    Button {<br>                        router.dismiss()<br>                    } label: {<br>                        Image(systemName: &quot;xmark.circle&quot;)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br>private extension ListView {<br>    <br>    func cell(index: Int) -&gt; some View {<br>        Button(&quot;Item \(index)&quot;) {<br>            router.presentDetail(description: &quot;Description \(index)&quot;)<br>        }<br>    }<br>}</pre><p>In this example, ListView reuses the same MainRouter type. Alternatively, we could create a separate router type for this navigation layer.</p><h4>DetailView</h4><p>We will not present DetailView modally and perform push navigation from it. So, we don’t wrap it in RoutingView.</p><p>We only pass the router responsible for navigation in this layer to the initializer.</p><pre>struct DetailView: View {<br>    <br>    private let description: String<br>    @StateObject private var router: MainRouter<br>    <br>    init(description: String, router: MainRouter) {<br>        self.description = description<br>        _router = StateObject(wrappedValue: router)<br>    }<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(description)<br>            Button(&quot;Present Alert&quot;) {<br>                router.presentAlert()<br>            }<br>        }<br>    }<br>}</pre><h4>AlertView</h4><p>AlertView is used only for presentation. It does not support nested navigation.</p><p>So, its implementation is straightforward, without the usage of router and RoutingView:</p><pre>struct AlertView: View {<br>    <br>    var body: some View {<br>        Text(&quot;Alert&quot;)<br>            .padding(.vertical, 20)<br>    }<br>}</pre><p>You can see above that we call router.presentAlert() from DetailView, a nested view in the navigation layer where the root view is ListView.</p><p>But the RoutingView embedded in the root ListView performs the actual presentation.</p><h3>Conclusion</h3><ul><li>The introduction of NavigationStack allows us to use only one router per a navigation layer</li><li>We got rid of AnyView in router state, making code less tricky</li><li>We replace view modifiers with RoutingView, which is easier to use and less error-prone</li><li>We get some known issues solved</li></ul><h3>Resources</h3><p>You can find the source code used for this article in my <a href="https://github.com/ihorvovk/Routing-in-SwiftUI-with-NavigationStack">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa8bb9b032de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/routing-in-swiftui-with-navigationstack-aa8bb9b032de">Routing in SwiftUI With NavigationStack</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Layered Dependency Injection With Swift Property Wrappers]]></title>
            <link>https://medium.com/better-programming/create-layered-dependency-injection-with-swift-property-wrappers-6e7a841f0934?source=rss-b1e4ac98d79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7a841f0934</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ihor Vovk]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 15:21:03 GMT</pubDate>
            <atom:updated>2021-12-11T01:24:47.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>Layered Dependency Injection With Swift Property Wrappers</h3><h4>Resolve dependencies at compile-time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bhtzF73jqYw2_FnL" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybezanger?utm_source=medium&amp;utm_medium=referral">Jeremy Bezanger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Purpose</h3><ul><li>A simple solution for dependency injection</li><li>Compile-time resolving of dependencies</li><li>Provide different scopes of injectable values for different layers: view model, view, router, interactor, etc.</li><li>Reduce the number of dependencies passed via init methods</li><li>Avoid spreading abstractions from an external library across the project.</li></ul><h3><strong>Solution</strong></h3><p>Even though the solution is property injection, it also provides benefits usually attributed to constructor injection. These become possible owing to property wrappers and keypaths. They allow resolving all the dependencies during compile-time. If any is missing, a project won’t build. It means that every instance with such dependencies will have them set up upon creation.</p><p>Since we inject dependencies via properties, a list of parameters passed to init methods is reduced. We won’t need to pass all dependencies at every place of instance creation.</p><p>A good project has a layered structure. For instance, if we follow clean architecture, we may come up with the following layers: view, view model, interactor (use case), app state, etc. And most likely, you don’t want all these layers to have access to the same dependencies. The solution uses keypaths to structure dependencies providing only those for every layer allowed by design.</p><p>Let’s see how it works. Code samples below are from a test project. You can find a link at the end of this article.</p><h4>Injected Property Wrapper</h4><p>Here is how we implement the property wrapper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a12f08cb7ed211cdd8f317beb161f5ed/href">https://medium.com/media/a12f08cb7ed211cdd8f317beb161f5ed/href</a></iframe><p>We use a keypath to identify a dependency injected. The prefix of such keypath determines a layer - a scope of dependencies. For example, injecting into a view model, we are going to use \.viewModel.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd926eaccb95bb98503b08bb74b7b40/href">https://medium.com/media/4bd926eaccb95bb98503b08bb74b7b40/href</a></iframe><p>Similarly, an interactor’s injections are accessible with the \.interactor. prefix in a keypath:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25ac8cae425abb295a589c02cfda352c/href">https://medium.com/media/25ac8cae425abb295a589c02cfda352c/href</a></iframe><p>A great thing here is that you don’t need to specify a type of injectable variable. The compiler infers it through the keypath.</p><h4>Root Dependency Container</h4><p>Layers are customizable. You specify them in the root DependencyInjection class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/857f20c439c85ce89a1975b2cfcd00e3/href">https://medium.com/media/857f20c439c85ce89a1975b2cfcd00e3/href</a></iframe><h4>Layers</h4><p>In our example, we provide injections for only two layers: interactors and view models. Protocols allow us to hide implementation details of the containers and, for example, to use mocked injections for tests. Here is the definition of the protocols:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11d6602b1b5292779613f1460da075a7/href">https://medium.com/media/11d6602b1b5292779613f1460da075a7/href</a></iframe><p>Both layers have access to appState. But only interactors may perform calls to network.</p><p>If we set up injections for the view layer, we probably wouldn’t add appState there, allowing views to access appState only via their view models.</p><p>The actual implementation of InteractorInjectionProtocol is straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2693ca8436cc778cdf8f637a7aaeca8/href">https://medium.com/media/b2693ca8436cc778cdf8f637a7aaeca8/href</a></iframe><p>For ViewModelInjectionProtocol, we provide two implementations, including a mock version for tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68acfad45662dd4279e68ce1ddc4b436/href">https://medium.com/media/68acfad45662dd4279e68ce1ddc4b436/href</a></iframe><p>We pass an instance of AppState via init because it is shared. The lazy keyword used here is not crucial for gitHubInteractor, but it would be reasonable to use it with injections that we may not always need during a single app run.</p><p>For complete understanding, let’s see the implementation of both GitHubInteractor and MockGitHubInteractor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83dd37fe8b5b4bc9983a1faaea5dbd3/href">https://medium.com/media/a83dd37fe8b5b4bc9983a1faaea5dbd3/href</a></iframe><p>Both interactors implement the same protocol. Inside they also use the dependency injection mechanism. They access injectable values from the interactor layer. Since all dependencies are injected directly into properties, we don’t need to pass them via an init method.</p><h4>Assembly</h4><p>To provide an assembly of all injections available in our project, we add it as a computed property to an extension of the DependencyInjection class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c34ae71acc5b294cfd95096b989e923c/href">https://medium.com/media/c34ae71acc5b294cfd95096b989e923c/href</a></iframe><p>We use different assemblies for the application itself and while running the project for previews. Because there is no need for network calls in previews.</p><h4>Tests</h4><p>Here is how we can set up our assembly in test cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1158c2b63aabc817a278e368510443f5/href">https://medium.com/media/1158c2b63aabc817a278e368510443f5/href</a></iframe><h3>Conclusion</h3><p>The developed solution has the following essential advantages:</p><ul><li>Even though it is a property injection, injected values become available upon an object construction. Resolving is performed during compilation. Traits of keypaths ensure it.</li><li>We don’t overload init methods with extra dependencies. Dependencies are injected directly into properties.</li><li>It allows you to control access to dependencies from different layers.</li><li>It is a simple solution and does not require a code of an external library.</li></ul><h3>Resources</h3><p>You can find the source code used in this article in my GitHub repository:</p><ul><li><a href="https://github.com/ihorvovk/Layered-Dependency-Injection">Layered Dependency Injection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7a841f0934" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-layered-dependency-injection-with-swift-property-wrappers-6e7a841f0934">Create Layered Dependency Injection With Swift Property Wrappers</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing in SwiftUI]]></title>
            <link>https://medium.com/better-programming/routing-in-swiftui-1dc87b7a47c7?source=rss-b1e4ac98d79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dc87b7a47c7</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ihor Vovk]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 21:42:39 GMT</pubDate>
            <atom:updated>2020-10-22T15:58:31.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>2 solutions for routing in SwiftUI</h4><figure><img alt="A street sign showing a crossroads." src="https://cdn-images-1.medium.com/max/1024/0*YK3JS-OPwkZl7T68" /><figcaption>Photo by <a href="https://unsplash.com/@soymeraki?utm_source=medium&amp;utm_medium=referral">Javier Allegue Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Purposes</h3><ul><li>Separate the navigation logic from the view layer. It’ll allow you to change navigation without modifying views.</li><li>Simplify the implementation of tasks, like deep linking, by making navigation more flexible</li></ul><h3>SwiftUI-Specific Information</h3><p>The declarative nature of SwiftUI makes it challenging to separate the navigation from the view layer. Push navigation requires inserting a NavigationLink into a view. And modal presentation needs the .sheet modifier to be added somewhere in the view code. You must provide a destination view for both the NavigationLink and .sheet. Also, in general, you’ll use the @state property to trigger navigation.</p><p>This is different from UIKit. For example, to present a view modally in UIKit, it’s enough to call present<strong><em> </em></strong>on the current view controller and pass a destination view controller to display. That can be easily done from outside of a presenting view controller.</p><h3>Solutions</h3><p>We’ll consider two somewhat different solutions to separate the navigation from the view layer. Both use the native SwiftUI navigation methods NavigationLink and .sheet modifier. But providing a destination view and navigation state will be moved to a router.</p><ol><li><strong>Router with trigger views:</strong> A router will return trigger subviews for all possible navigation routes to insert them into a presenting view. Such a subview code snippet will contain a NavigationLink or .sheet modifier inside, as well as a destination view specified, and will use a @state property, stored in the router, via binding. This way, the presenting view won’t depend on the navigation code and destination, only on a router protocol.</li><li><strong>Router with type-erased modifiers:</strong> A presenting view will be configured with general modifiers for presenting any other views. Being initialized with a router, those modifiers will track the navigation state stored in the router via bindings and will perform navigation when the router changes that state. The router also will have functions for all possible navigation. Those functions will change the state and trigger navigation as a result.</li></ol><h4>Example of usage</h4><p>To make it easier to understand, let’s consider both solutions in the context of a simple example.</p><p>The project will consist of two simple views: a presenting view with a single button and a presented view that should be navigated to when the user taps the button. The presented view will display a text passed from the presenting view. Tapping on that text will dismiss the presented view.</p><h3>1. Router With Trigger Views</h3><h4>Presenting view</h4><p>The presenting view is initialized with a router that knows how to navigate to the presented view. The router provides a trigger view that, being inserted, can perform the desired navigation in response to user interactions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e21e3b26381ac9f8f9c8e85c186f118b/href">https://medium.com/media/e21e3b26381ac9f8f9c8e85c186f118b/href</a></iframe><p>Using PresentingRouterProtocol instead of the actual router class allows us to change the navigation logic easily and to initialize the PresentingView with a mock router for tests.</p><p>We should wrap the router property with @StateObject (available from iOS 14). This is because the navigation state resides in a router, and the view should update on the state changes. Also, in contrast to @ObservedObject,<strong><em> </em></strong>this wrapper<strong><em> </em></strong>avoids recreating a router every time the owner view is updated. It’s crucial for our implementation of push navigation based on NavigationLink.</p><h4>Router protocols</h4><p>There are two protocols. The first one is used by routers that can navigate to other views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83cad4de41009e3cf87f96b76e2289b3/href">https://medium.com/media/83cad4de41009e3cf87f96b76e2289b3/href</a></iframe><p>NavigationState<strong><em> </em></strong>will be implemented as a structure in subclasses. It’ll contain state variables for all possible navigation routes. binding<strong><em> </em></strong>is a convenient<strong><em> </em></strong>function used to get bindings for the existing state variables.</p><p>The other protocol is used for routers of views that were presented modally or pushed on a navigation view. It allows us to navigate back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1a2a535b1cfdf17c6ed95d0f45c6f08/href">https://medium.com/media/f1a2a535b1cfdf17c6ed95d0f45c6f08/href</a></iframe><p>Usually, routers will conform to both the PresentingRouter and the PresentedRouter protocol.</p><h4>Router implementation</h4><p>A router conforming to PresentingRouterProtocol should be able to navigate to the details view. So its navigationState should contain a variable for this route.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a471b818b0c9f75cfa7a234112e81869/href">https://medium.com/media/a471b818b0c9f75cfa7a234112e81869/href</a></iframe><p>The presentDetails<strong><em> </em></strong>function uses the binding function from the NavigatingRouter protocol extension to provide access to the corresponding state variable, both to the router of the destination view and to the returning trigger view. The destination router will use this binding for dismissing. And the trigger view will use the binding to trigger navigation.</p><h4>Trigger views</h4><p>A router returns trigger views that perform actual navigation in response to user actions. We’ll review only two of the most useful types of trigger views, although there can be more of them. Both take a content view and transform it into a resulting button that can navigate to the specified destination view.</p><p>The first one is SheetButton<strong><em>, </em></strong>used in the example above. It implements modal navigation with the SwiftUI .sheet modifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf1e2154a5b583485f69a8f673651fb6/href">https://medium.com/media/cf1e2154a5b583485f69a8f673651fb6/href</a></iframe><p>The second one is NavigationButton. It provides push navigation implemented with the NavigationLink inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b6da36513777f80f82936da4ad91dcb/href">https://medium.com/media/4b6da36513777f80f82936da4ad91dcb/href</a></iframe><p>We use the NavigationLink<strong><em> </em></strong>initializer<strong><em> </em></strong>with the<strong><em> </em></strong>isActive<strong><em> </em></strong>binding here since we want to keep the navigation state in a router.</p><p>Having the same initialization parameters in SheetButton and NavigationButton makes it easy to change the type of navigation from modal presentation to push navigation — and vice versa.</p><h4>BasePresentedRouter class</h4><p>Dismissing functionality is very common. So we’ll also introduce a simple base router class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae47243eb16624c1ab310c5c4e3d6063/href">https://medium.com/media/ae47243eb16624c1ab310c5c4e3d6063/href</a></iframe><h4>Presented view</h4><p>The details view can only be presented and doesn’t perform any other kind of navigation. Because of this, we’ll use the base BasePresentedRouter<strong><em> </em></strong>router without subclassing here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc0eab4d8f13c1e60e75c2bad0e3ebe6/href">https://medium.com/media/fc0eab4d8f13c1e60e75c2bad0e3ebe6/href</a></iframe><p>We can declare the<strong><em> </em></strong>router property without a<strong><em> </em></strong>wrapper in PresentedView because we use it only for dismissing, so the view doesn’t need to listen to the router’s state changes.</p><p>We hide the view when the user taps on its text.</p><h3>2. Router With Type-Erased Modifiers</h3><p>Navigation in this solution is implemented differently — with modifiers. I call them <em>type-erased</em> because they don’t depend on specific destination views. Being added once, they can navigate to any view.</p><h4>Presenting view</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95c217a4a515c5bdfc6eba6c3a72ad64/href">https://medium.com/media/95c217a4a515c5bdfc6eba6c3a72ad64/href</a></iframe><p>To allow pushing any view onto a navigation view, we should add a .navigation modifier and pass the router as a single parameter. Similarly, to enable presenting a sheet, we use a .sheet modifier. We can add it to any subview inside of the body. It’s a custom .sheet<strong><em> </em></strong>modifier that takes a router as a parameter.</p><p>The presenting view navigates to the presented view by calling the router’s presentDetails function from the button’s action.</p><h4>Router implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/656536c85380e88b020db307ccc69c6b/href">https://medium.com/media/656536c85380e88b020db307ccc69c6b/href</a></iframe><p>The base Router class implements the ObservableObject protocol, and its state is wrapped with @Published, in order to allow state changes to be propagated to a view and to update navigation.</p><p>The navigating variable is driving push navigation onto a NavigationView. Its value should be a destination view.</p><p>presentingSheet is driving sheet presentation. Its value also should be a destination view.</p><p>isPresented is a bool binding to the state variable that’s driving navigation to the current view. It should be passed from a presenting router.</p><p>Push or modal navigation can be triggered by setting a destination view to the navigation or presentingSheet state property, accordingly. Below is a convenient interface for router subclasses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c554be1b5a7fb0b8202a3768e8311d89/href">https://medium.com/media/c554be1b5a7fb0b8202a3768e8311d89/href</a></iframe><p>As you can see above, a router should be initialized with a binding to the Bool property that’s driving presentation of the owner view. We can obtain it from a presenting router with the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/268f6c7c4664c58b942358484ed25f18/href">https://medium.com/media/268f6c7c4664c58b942358484ed25f18/href</a></iframe><p>boolBinding here is a private function implemented with key-path access to the state. Below is the router’s private extension that also contains the binding<strong><em> </em></strong>function used for the .navigation and .sheet modifiers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608cb85a9481ccef620d3367f75c2b84/href">https://medium.com/media/608cb85a9481ccef620d3367f75c2b84/href</a></iframe><h4>.navigation and .sheet modifiers</h4><p>.navigation and .sheet<strong><em> </em></strong>are actually functions added to the View extension. They take a router as a parameter to bind the resulting view modifiers with the corresponding navigation state in the router: navigation<strong><em> </em></strong>and<strong><em> </em></strong>presentingSheet<strong><em> </em></strong>variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37af2a994b43f84be4f5a434d4e2dc35/href">https://medium.com/media/37af2a994b43f84be4f5a434d4e2dc35/href</a></iframe><p>NavigationModifier<strong><em> </em></strong>is implemented with the NavigationLink<strong><em> </em></strong>inside and uses the provided binding for triggering presentation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efef963c0a73796a1c78f203770e31b9/href">https://medium.com/media/efef963c0a73796a1c78f203770e31b9/href</a></iframe><p>SheetModifier<strong><em> </em></strong>is implemented with the SwiftUI .sheet<strong><em> </em></strong>modifier in a very similar way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/881f6767fd67aa5d094830c0d0c1a9af/href">https://medium.com/media/881f6767fd67aa5d094830c0d0c1a9af/href</a></iframe><p><strong>Subclassing router</strong></p><p>The above implementation of the base Router class allows its subclasses to be very simple. We only need to add functions for available navigation options.</p><p>In our example, it’ll be a single presentDetails function. To perform navigation, we need to create a destination view, initialize it with a corresponding router, and use one of the convenience methods of the base class (navigateTo or presentSheet) to trigger the desired type of navigation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5350ab34276df470e181660f0f23aef3/href">https://medium.com/media/5350ab34276df470e181660f0f23aef3/href</a></iframe><p>Then, we can call it from any point-of-view code when we want to present the PresentedView. It’s the button’s action closure in our example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e19e8d570c93a667aa3bd1857e4605be/href">https://medium.com/media/e19e8d570c93a667aa3bd1857e4605be/href</a></iframe><p>If we want to switch from push navigation to modal, the only thing we need to do is replace the navigateTo<strong><em> </em></strong>call with presentSheet.</p><h4>Presented view</h4><p>It’s the same as in the first solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f111c4e3bfdcc900d759721a21bebe7/href">https://medium.com/media/4f111c4e3bfdcc900d759721a21bebe7/href</a></iframe><h3>Deep Linking</h3><p>Both solutions have a navigation state inside routers. This allows us to perform navigation and implement deep linking simply by changing a router’s state. The first solution, though, needs proper trigger views to be added to allow possible deep link routes. The second solution uses type erasure for destination views. So only the general .navigation and .sheet modifiers are needed.</p><h3>Comparison</h3><p>Both solutions separate navigation logic from the view layer. Both store the navigation state in a router. Both need some code to be inserted into a view for navigation. That code uses the NavigationLink or the .sheet modifier inside.</p><p>Changing the navigation type from modal to push navigation, and vice versa, is trivial in both solutions.</p><p>In the first solution, navigation is performed with trigger views that are returned by a router. And generic type-erased modifiers are used in the second solution. In the first solution, we need to preconfigure a view with all of the possible routes by inserting corresponding trigger subviews. In the second solution, adding a new route doesn’t require changing a view because the<strong><em> </em></strong>.navigation and .sheet modifiers support any destination view.</p><p>For example, suppose some view can navigate to three different views, pushing them onto a navigation stack. In that case, we’ll need to insert three trigger views in the first solution and only one .navigation modifier in the second solution. This difference makes navigation more flexible in the second solution.</p><p>Subclassing is simpler in the second solution because there’s the base router superclass that stores all of the navigation state.</p><p>A drawback of the second solution is the base class needs to store all three navigation state variables: navigating, presentingSheet, and isPresented, even though not all of them are necessary to be used by a particular subclass.</p><h3>Resources</h3><p>You can find the source code used in this article in my GitHub repositories:</p><ul><li><a href="https://github.com/ihorvovk/Routing-in-SwiftUI-with-trigger-views">Routing with trigger views</a></li><li><a href="https://github.com/ihorvovk/Routing-in-SwiftUI-with-type-erased-modifiers">Routing with type erased modifiers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dc87b7a47c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/routing-in-swiftui-1dc87b7a47c7">Routing in SwiftUI</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>