How to pass global variable data between controllers

I declare a global variable in my first view controller:

import UIKit
import QuartzCore

var searchResults = [SearchResult]()

class HomeSearchViewController: UIViewController {

print(searchResults.count) will print 18

However in my second view controller:

 override func viewDidLoad() {
        super.viewDidLoad()
        print(searchResults.count)    

prints nothing. The views are connected via a Tab Bar VC. I don’t want to subclass the Tab Bar or use AppDelegate to pass the data.

Thanks.

Hi @mmuldoon,
Hoping that you are still looking for an answer, There are a couple of ways to achieve that in a better way.

  1. Use a singleton, which means the global variable is accessible from the singleton (the most common example is when you use UIApplication.shared

  2. Pass the data when the segue is called

  3. Use dependency injection

If you need more details, reply back and we’ll look at those, There are some wonderful articles on this site, if you search for them, you should find them

cheers,

Jayant

1 Like