How do I use coordinators for navigation in Swift?

In Swift, using coordinators for navigation helps to manage the flow of your app and improve its structure. A coordinator is basically a design pattern that helps to encapsulate navigation logic and its associated view controllers. This makes your code easier to manage and scale as your app grows.

Here’s how you can implement a basic coordinator pattern in Swift:

// Coordinator protocol protocol Coordinator { var navigationController: UINavigationController { get set } func start() } // App Coordinator class AppCoordinator: Coordinator { var navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } func start() { let mainViewController = MainViewController() navigationController.pushViewController(mainViewController, animated: false) } } // Example of MainViewController class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Setup view here } @objc func navigateToDetails() { let detailsViewController = DetailsViewController() navigationController?.pushViewController(detailsViewController, animated: true) } } // Setting up the App Coordinator in AppDelegate or SceneDelegate class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? var appCoordinator: AppCoordinator? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = scene as? UIWindowScene else { return } window = UIWindow(windowScene: windowScene) let navigationController = UINavigationController() appCoordinator = AppCoordinator(navigationController: navigationController) appCoordinator?.start() window?.rootViewController = navigationController window?.makeKeyAndVisible() } }

Swift coordinators navigation iOS development app architecture