How do you share data between view controllers and other objects in Swift?

Your question is very broad. To suggest there is one simple catch-all solution to every scenario is a little naïve. So, let’s go through some of these scenarios.


The most common scenario asked about on Stack Overflow in my experience is the simple passing information from one view controller to the next.

If we’re using storyboard, our first view controller can override prepareForSegue, which is exactly what it’s there for. A UIStoryboardSegue object is passed in when this method is called, and it contains a reference to our destination view controller. Here, we can set the values we want to pass.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MySegueID" {
        if let destination = segue.destination as? SecondController {
            destination.myInformation = self.myInformation
        }
    }
}

Alternatively, if we’re not using storyboards, then we’re loading our view controller from a nib. Our code is slightly simpler then.

func showNextController() {
    let destination = SecondController(nibName: "SecondController", bundle: nil)
    destination.myInformation = self.myInformation
    show(destination, sender: self)
}

In both cases, myInformation is a property on each view controller holding whatever data needs to be passed from one view controller to the next. They obviously don’t have to have the same name on each controller.


We might also want to share information between tabs in a UITabBarController.

In this case, it’s actually potentially even simpler.

First, let’s create a subclass of UITabBarController, and give it properties for whatever information we want to share between the various tabs:

class MyCustomTabController: UITabBarController {
    var myInformation: [String: AnyObject]?
}

Now, if we’re building our app from the storyboard, we simply change our tab bar controller’s class from the default UITabBarController to MyCustomTabController. If we’re not using a storyboard, we simply instantiate an instance of this custom class rather than the default UITabBarController class and add our view controller to this.

Now, all of our view controllers within the tab bar controller can access this property as such:

if let tbc = self.tabBarController as? MyCustomTabController {
    // do something with tbc.myInformation
}

And by subclassing UINavigationController in the same way, we can take the same approach to share data across an entire navigation stack:

if let nc = self.navigationController as? MyCustomNavController {
    // do something with nc.myInformation
}

There are several other scenarios. By no means does this answer cover all of them.

Leave a Comment