Search code examples
iosswiftuisearchcontroller

Access a variable declared in one view controller from another view controller


I want to access the searchController variable declared in a tableviewcontroller

var searchController:UISearchController? = nil

 override func viewDidLoad() {
        super.viewDidLoad()  

       let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "SegueTableViewController") as! SegueTableViewController
        searchController = UISearchController(searchResultsController: locationSearchTable)
        searchController?.searchResultsUpdater = locationSearchTable
}

in the second view controller, which is also a tableviewcontroller, I want to access the searchController from the first view controller.

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows


        if searchController.isActive && searchController.searchBar.text != ""{
            return filteredUsers.count
        }
        return self.usersArray.count

    }

Solution

  • You can declare a global variable by placing the declaration outside your ViewController instead. I don't necessarily like this solution, but at this moment it's the only one I can think of.