<?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 Nikolai Sokol on Medium]]></title>
        <description><![CDATA[Stories by Nikolai Sokol on Medium]]></description>
        <link>https://medium.com/@nikolaisokol?source=rss-83ad74551f28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*n-PqCFydSM5sCIvHhyz7FQ.jpeg</url>
            <title>Stories by Nikolai Sokol on Medium</title>
            <link>https://medium.com/@nikolaisokol?source=rss-83ad74551f28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:14:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikolaisokol/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 navigation with Coordinators]]></title>
            <link>https://medium.com/@nikolaisokol/swiftui-navigation-with-coordinators-b568e9ebd4b4?source=rss-83ad74551f28------2</link>
            <guid isPermaLink="false">https://medium.com/p/b568e9ebd4b4</guid>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Nikolai Sokol]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 19:14:58 GMT</pubDate>
            <atom:updated>2022-12-25T00:16:10.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTu2LIDZtgNDQVMUCJF2Ow.png" /></figure><p>Navigation is a key component of any application. With iOS 16, Apple has <a href="https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types">introduced</a> a new navigation flow with the NavigationStack structure.</p><p>Here, I’d like to demonstrate how we can use a new approach. I suggest creating a project more complex than a “Hello World” one, with a more intricate navigation concept.</p><p>My main idea is to avoid using navigation inside the View layer. Instead, the View should simply notify the ViewModel of the user’s actions. The ViewModel then carries out some logic (such as preparing the data for a new module that needs to be displayed) and passes an event to the Coordinator, who is responsible for carrying out the necessary navigation operations. This approach allows for a more structured way of handling user interactions and navigation, ensuring that the codebase is easy to maintain and debug.</p><p>The concept is based on the ideas presented in <a href="https://betterprogramming.pub/flow-navigation-with-swiftui-4-e006882c5efa">this article</a>. It is an interesting and informative piece that delves into the topic of navigation with SwiftUI.</p><p>First, we need to create an entry point for our App. I’ve chosen a TabBar as the root coordinator. It contains two root tabs, which are the main containers for navigation. In my example, the second tab is empty and only contains a container for future navigation. I’d say it’s for your playground, but the truth is I’m lazy.</p><p>I separated Coordinators and Modules into Root and Usual categories. When we call the start() method, the coordinator creates its module. Root coordinators return AnyView, while the others add their view to the navigation stack (we’ll discuss it later).</p><pre>// MARK: - RootCoordinator<br><br>extension TabBarCoordinator: RootCoordinator {<br>    func start() -&gt; AnyView {<br>        showTabBar()<br>    }<br>}<br><br>private func showTabBar() -&gt; AnyView {<br>    let unit = rootModulesFactory.makeTabBar(output: self)<br>    tabBarInput = unit.input<br>        <br>    prepareTabs()<br>        <br>    return unit.view<br>}</pre><pre>// MARK: - Coordinator<br><br>extension FirstTestCoordinator: Coordinator {<br>    func start() {<br>        showFirstTestModule()<br>    }<br>}<br><br>private func showFirstTestModule() {<br>    let unit = modulesFactory.makeFirstTestModule(output: self)<br>    firstTestModuleInput = unit.input<br>    router.present(unit.view)<br>}</pre><p>Each module has a Configurator to set up the module</p><pre>typealias RootModule&lt;T&gt; = (view: AnyView, input: T)<br><br>final class TabBarConfigurator {<br>    func configure(output: TabBarOutput) -&gt; RootModule&lt;TabBarInput&gt; {<br>        let viewState = TabBarViewState()<br>        <br>        let viewModel = TabBarViewModel(<br>            viewState: viewState,<br>            output: output<br>        )<br>        <br>        let view = TabBarView(viewState: viewState, output: viewModel)<br>        <br>        return (AnyView(view), viewModel)<br>    }<br>}</pre><pre>typealias NavigableModule&lt;T&gt; = (view: NavigableView, input: T)<br><br>final class FirstTestModuleConfigurator {<br>    func configure(output: FirstTestModuleOutput) -&gt; NavigableModule&lt;FirstTestModuleInput&gt; {<br>        let viewState = FirstTestModuleViewState()<br>        <br>        let viewModel = FirstTestModuleViewModel(<br>            viewState: viewState,<br>            output: output<br>        )<br>        <br>        let view = FirstTestModuleView(viewState: viewState, output: viewModel)<br>        <br>        return (NavigableView(view: AnyView(view)), viewModel)<br>    }<br>}</pre><p>a ViewModel for logic</p><pre>final class TabBarViewModel {<br>    private let viewState: TabBarViewState<br>    private weak var output: TabBarOutput?<br>    <br>    private var selectedTab = TabBarElementType.mainScreenRoot<br>    <br>    private var selectedTabSubscription: AnyCancellable?<br>    <br>    init(<br>        viewState: TabBarViewState,<br>        output: TabBarOutput<br>    ) {<br>        self.viewState = viewState<br>        self.output = output<br>    }<br>    <br>    private func subscribeToSelectedTab() {<br>        selectedTabSubscription = viewState.$selectedTab<br>            .sink { [weak self] in<br>                if self?.selectedTab == $0 {<br>                    self?.output?.didTapSelectedTab($0)<br>                } else {<br>                    self?.selectedTab = $0<br>                }<br>            }<br>    }<br>}</pre><p>a ViewState to store @Published properties without overloading the ViewModel</p><pre>final class TabBarViewState: ObservableObject {<br>    @Published var tabs: [TabBarElement] = []<br>    @Published var selectedTab = TabBarElementType.mainScreenRoot<br>}</pre><p>and, of course, a view.</p><pre>struct TabBarView: View {<br>    @ObservedObject private var viewState: TabBarViewState<br>    private let output: TabBarViewOutput<br>    <br>    init(<br>        viewState: TabBarViewState,<br>        output: TabBarViewOutput<br>    ) {<br>        self.viewState = viewState<br>        self.output = output<br>    }<br>    <br>    var body: some View {<br>        TabView(selection: $viewState.selectedTab) {<br>            ForEach(viewState.tabs) { element in<br>                element.view<br>                    .tabItem {<br>                        element.item<br>                    }<br>                    .tag(element.type)<br>            }<br>        }<br>    }<br>}</pre><p>Additionally, Modules and Coordinators have Input and Output interfaces for transferring data between them, reacting to changes, and for transitions.</p><pre>// MARK: - TabBarInput<br><br>extension TabBarViewModel: TabBarInput {<br>    func updateTabs(_ tabs: [TabBarElement]) {<br>        subscribeToSelectedTab()<br>        viewState.tabs = tabs<br>    }<br>}<br><br>// MARK: - TabBarOutput<br><br>extension TabBarCoordinator: TabBarOutput {<br>    func didTapSelectedTab(_ tab: TabBarElementType) {<br>        switch tab {<br>        case .mainScreenRoot:<br>            mainScreenCoordinatorInput?.popToRoot()<br>            <br>        case .settingsScreenRoot:<br>            settingsScreenCoordinatorInput?.popToRoot()<br>        }<br>    }<br>}</pre><p>Modules are constructed using fabrics</p><pre>typealias RootModule&lt;T&gt; = (view: AnyView, input: T)<br><br>extension RootModulesFactory: RootModulesFactoring {<br>    func makeTabBar(output: TabBarOutput) -&gt; RootModule&lt;TabBarInput&gt; {<br>        TabBarConfigurator().configure(output: output)<br>    }<br>    <br>    ...<br>}</pre><p>Coordinators use a Router for navigation, which is created in the root Coordinator (e.g. MainScreenCoordinator) and then passed to subsequent coordinators. The Router contains an array of NavigableViews (which will be discussed later) and a few basic methods.</p><pre>final class Router: ObservableObject {<br>    @Published var navigableViews: [NavigableView] = []<br>}<br><br>extension Router: Routable {<br>    func present(_ view: NavigableView) {<br>        navigableViews.append(view)<br>    }<br>    <br>    func popToRoot() {<br>        navigableViews.removeAll()<br>    }<br>    <br>    func pop() {<br>        navigableViews.removeLast()<br>    }<br>}</pre><p>The Main Screen Root Module is the core of the navigation on the Main tab. Its View contains a new structure, the NavigationStack. The MainScreenView is used as a child view for convenience and clarity.</p><pre>struct MainScreenRootView: View {<br>    @ObservedObject private var state: MainScreenRootViewState<br>    @ObservedObject private var router: Router<br>    <br>    private let output: MainScreenRootViewOutput<br>    <br>    ...<br>    <br>    var body: some View {<br>        if let model = state.mainScreenModel {<br>            NavigationStack(path: $router.navigableViews) {<br>                MainScreenView(viewState: model.viewState, output: model.viewOutput)<br>                    .navigationDestination(for: NavigableView.self) {<br>                        $0.view<br>                    }<br>            }<br>        }<br>    }<br>}</pre><p>NavigationStack has the <a href="https://developer.apple.com/documentation/swiftui/list/navigationdestination(for:destination:)">navigationDestination</a> method, which &quot;describes the view that the stack displays when presenting a particular kind of data&quot;.</p><p>The data in this case is a small structure called NavigableView.</p><pre>struct NavigableView: Navigable {<br>    let id = UUID()<br>    let view: AnyView<br>}</pre><p>navigationDestination requires NavigableView to be Hashable, so we create a protocol called Navigable</p><pre>protocol Navigable: Identifiable, Hashable {}<br><br>extension Navigable {<br>    static func == (lhs: Self, rhs: Self) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br>    <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}</pre><p>We simply add a NavigableView to the Router’s array, and the view will react and perform navigation. Stack of views can be manipulated in many ways. We can clear the array and navigate to the root view, or simply remove the last element to skip the current screen.</p><p>The project was much larger than anticipated. I explored many navigation cases. For example, it’s possible to clear the stack when tapping an already selected tab. Or, we can push the same screen one after another, like when browsing products in a grocery app. You view one product, then tap on a similar one, and so on. SecondTestModule simulates that scenario.</p><p>In ThirdTestModule I showed how we can use subview that doesn’t have its own coordinator. This approach comes in handy when we want to make a screen divided with modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ohkVwXWI7lf55jpFgScfew.gif" /></figure><p>This approach, while not perfect, is certainly effective. I’m open to any feedback and advice that could help me refine it further and make it even more successful. I would be grateful for any criticism or help in order to ensure that the process is as seamless and successful as possible.</p><p>See the <a href="https://github.com/NikolaiSokol/SwiftUINavigation">GitHub</a> to really get your hands dirty and try out everything that you can find.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b568e9ebd4b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>