Unwinding to a previous Controller in a Swift mobile app with VIPER

In this quick tutorial I’d like to show you how I manage unwinding views in mobile apps built with Swift by using VIPER design pattern. This simple trick can help you especially when you’re used to traditional MVC Storyboard’s segues.

Segues in Xcode

Creating segues in Xcode is very simple. Both - using Storyboards or just programmatically. Apple provides unwinding segues and usually there is no need to implement it.

But sometimes there are special cases in mobile app development, when you want to dismiss the current view and get back to the previous UIViewController. In MVC, we normally use the following function:

dismiss(animated flag: Bool, completion: (() -> Void)? = nil)

There is also an option to unwind on UINavigationController.

Uwinding segues in VIPER

Using VIPER is a little bit different. Mostly because communication between Controllers in VIPER should happen in Router. And Router isn’t UIViewController, so it doesn’t have automatic access to the stack with the current Controller.

What does it mean for Swift developers? Before performing an unwind we should „tell” our Router what is the initial Controller, so that Router will know to what view it should roll back.

We can do this in very simple way. First, we must create a handler in RouterInput:

var handler: UIViewController? { get set }

To this handle, we pass information about initial UIViewController. So in Configuraton, inside function configure(viewController: UIViewController) we add these lines:

router.handler = viewController

Next, in Router class we create a function called for example dismissModular(). It looks like this:

    func dismissModular() {
        handler?.navigationController?.popViewController(animated: false)
    }

As you can see, handler is passed within this function, so it can be easily implemented in Presenter. Because now Router „knows” what UIViewController is initial.

Wrapping up

That’s all, have fun. If you have any questions or corrections, please feel free to add them in comments section. If you're not familiar with design pattern VIPER, check out my last blog post on this subject.

Picture by Freestocks on Unsplash.com

Recommended reads

Contact us

* Required fields