Created 2025-02-04T06:26:07Z
Updated 2025-02-04T06:43:18Z
Type Research
Status In Progress

To implement a SwiftUI application with MVVM and a coordinator without relying on third-party dependencies, follow these steps:

  1. Define the Model: Create the data models that conform to the ObservableObject protocol. Example:
    import Foundation
    
    class Item: ObservableObject {
        @Published var timestamp: Date
           
        init(timestamp: Date) {
            self.timestamp = timestamp
        }
    }
    
  2. Create the ViewModel: The ViewModel will manage the state and business logic for the views. Example:
    import SwiftUI
    import Combine
    
    class ItemViewModel: ObservableObject {
        @Published var items: [Item] = []
           
        func addItem() {
            let newItem = Item(timestamp: Date())
            items.append(newItem)
        }
           
        func deleteItem(at offsets: IndexSet) {
            items.remove(atOffsets: offsets)
        }
    }
    
  3. Build the Coordinator: The Coordinator will handle navigation and presentation logic. Example:
    import SwiftUI
    
    class Coordinator: ObservableObject {
        @Published var currentView: AnyView?
           
        func showDetail(for item: Item) {
            currentView = AnyView(Text("Item at \(item.timestamp)"))
        }
    }
    
  4. Integrate the ViewModel and Coordinator into the View: Bind the ViewModel and Coordinator to the views using the @StateObject and @EnvironmentObject properties. Example:
    import SwiftUI
    
    struct ContentView: View {
        @StateObject private var viewModel = ItemViewModel()
        @StateObject private var coordinator = Coordinator()
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(viewModel.items) { item in
                        Button(action: {
                            coordinator.showDetail(for: item)
                        }) {
                            Text("Item at \(item.timestamp, style: .date)")
                        }
                    }
                    .onDelete(perform: viewModel.deleteItem)
                }
                .navigationBarItems(trailing: Button("Add") {
                    viewModel.addItem()
                })
                .navigationTitle("Items")
                .sheet(item: $coordinator.currentView) { view in
                    view
                }
            }
        }
    }
    

This structure allows the separation of concerns and management of state and navigation in a SwiftUI application, without third-party dependencies.

See also https://quickbirdstudios.com/blog/coordinator-pattern-in-swiftui/