Coordinator Pattern in swift

Kanan Abilzada
3 min readJul 5, 2021

--

The coordinator pattern is for separating all of your navigation codes from the controller. In this tutorial we’ll learn:

  1. How implement it to our project?
  2. How pass variables to other controllers with coordinators?

Okay, let’s get started. Firstly I am creating a brand new project for us :) I won’t use storyboards in this tutorial.

Let’s create a Coordinator’s main functions and variables.

“start” function will be all coordinator’s initial function and call controller.

“navigationController” can be used in all coordinator

And create AppCoordinator.swift. AppCoordinator will confirm with Coordinator. It will call from our SceneDelegate (or AppDelegate)

so, open SceneDelegate (if you’re using AppDelegate, open it) and call it.

First, add this line to the top of the codes.

And in scene function add this line of code.

Okay, let’s create FirstController and SecondController and their coordinators. FirstController will be our initial controller for AppCoordinator.

FirstController:

I have added just a button center of the screen and we’ll add the coordinator’s code to the button action.

SecondController:

There is a “Return to FirstController” button on the center of the screen.

Controllers are ready and now create their coordinators…

FirstCoordinator:

SecondCoordinator:

Okay, we created all controller’s coordinators. Now I am going to write FirstController’s button action. For this firstly we call coordinators in their controller.

weak var coordinator: FirstCoordinator?

weak var coordinator: SecondCoordinator?

We must attend to memory leaks in here. To prevent it I’ll add weak to

Open FirstCoordinator and write the “showSecondController” method like this:

And call this function in FirstController’s button action:

And the same action will be for returning from SecondController:

Voila :) Our code is working in now. And in now I am going to pass variable from FirstController to SecondController. For doing this I must add variable to SecondCoordinator and update SecondController’s title in here.

And update another codes for this:

And updating my code on FirstController:

Now works my app like this.

This pattern helps you to avoid re-writing the code. In the next part I gonna use this with MVVM pattern and with TabBar. See you next tutorial. Don’t forget smile :)

--

--