How to pass data between view controllers in Swift using segues

View controllers are an essential part of SwiftUI and UIKit, Apple's libraries for application development across all its platforms (iOS, macOS, iPadOS, tvOS, and watchOS). Almost every Apple application has at least one view controller. Let's see why these are so important.

View controllers

View controllers allow managing the application's interface. Generally, they manage a single root view but may have subviews. The view controller handles the user's navigation within the application through their interaction. The SwiftUI and UIKit framework allows multiple view controllers to manage different parts of our application's content and for other uses.

For example, a container view controller can hold content from other view controllers. The framework also allows multiple user interfaces, each with its view controller. With numerous view controllers, we might need to transfer data between these controllers. There are many ways to pass data from one view controller to another. We will cover the one that uses segues in storyboards.

Passing data in storyboards using segues

With storyboards, we can pass data between controllers using segues. On the sender view controller, we will need to override the prepare(for segue) method. Here is what it will look like.

class SenderViewController: UIViewController
{
// variables
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// A text variable that will be passed, here it is inputted from a text field
let property_to_pass = textField.text ?? ""
// Receiver view controller and its variable that receives the data
let receiverViewController = segue.destination as! ReceiverViewController
receiverViewController.property_to_receive = property_to_pass
}
// other methods
}

The receiver view controller should look like the code below.

class ReceiverViewController: UIViewController {
var property_to_receive: String = ""
// other variables and methods
}

Now, the value of property_to_pass in SenderViewController will also be stored in property_to_receive in ReceiverViewController.

Conclusion

The view controllers are crucial for managing interface and user navigation in SwiftUI and UIKit frameworks. With multiple view controllers, data transfer becomes essential. Segues in storyboards offer an effective method for passing data between view controllers. By overriding the prepare(for segue) method and setting up properties in the receiver view controller, seamless data transfer enhances interactivity and functionality. Understanding and implementing data-passing techniques using segues in Swift empowers developers to build dynamic and interconnected view controller systems.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved