Sending Data via Segue

When creating transitions between different view controllers in your Swift app storyboard, you may want to send data across each segue. This post outlines how you would typically do this in a Swift app, and provides an extension that improves on this further.

In the ‘source’ view controller, a ‘prepare’ method must be created that defines the data sent to the ‘destination’ view controller. This can be seen in the code below.

This method accepts the ‘destination’ view controller and allows you give the destination view controller the required data. A switch statement can be used when working with the many different segues originating from the ‘source’ view controller.

When working with multiple segues, the prepare method can become large and clunky. A better option, which is more readable, is to pass the data into the segue so that you dont have to handle all the data in the prepare method, for all the different segues. The code below extends on the UIViewController and does exactly this.

The above code is used in a view controller in the following way:

This is a solution that has worked for me and the full code is linked below. I would love to hear your thoughts on this. Please feel free to comment below.