K. Smith
K. Smith

Reputation: 13

Declaring a global variable in swift while using UITableView

I'm confused on how to declare a global variable outside of a function in my swift project. This is the code I'm using to save the text of a selected row of UITableView as the variable "chosenFeed": 1

Then, I'm trying to use this variable to open a URL on another View Controller like: 2

I learned that I did this incorrectly because "chosenFeed" is local to that override function. So, I am clueless of how to declare this global variable to be accessed by a different VC. Some people recommended structs, so I tried this in the tableView VC:

struct GlobalVariable {
    static var indexPath = tableView.indexPathForSelectedRow
    static var currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell
    static var choosenFeed = tableDict[currentCell.textLabel!.text!]
}

but that didn't work either bc of too many ambiguous references. Any solutions?

Upvotes: 1

Views: 1514

Answers (1)

bdc
bdc

Reputation: 188

As the other posters have mention using global variables is not the best idea. It's not good coding practice, and can become very confusing once your app scales. When passing information between a TableView and another View (a ViewController, a Cell etc.) you have two options (not including using global variables).

First option: Use prepareForSegue

On your destination ViewController you need to create a variable called chosenFeed. Then at the bottom of your TableView you can use this prepareForSegue function to pass the data:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if let destinationVC = segue.destinationViewController as ViewController {
       destinationVC.chosenFeed = self.chosenFeed
   }
}

OR You could use didSelectRowAtIndexPath

If this data needs to be sent and is based on which cell is selected you can use didSelectRowAtIndexPath. You still need to add on your destination ViewController a variable called chosenFeed. If you choose this option you also need to name your segue in the Storyboard.

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   // Youll need the name of your ViewController here to pass the variable
   let destinationVC = "nameOfTheDestination_VC()"
   destinationVC.chosenFeed = self.chosenFeed

   //This is where you use the named segue from the Storyboard
   destinationVC.performSegueWithIdentifier("segueName", sender: self)

}

Either of those suggestions should be what you're looking for. If after all that, you still decide you need a global variable (after all this was the question asked) you just need to declare the variable above the class declaration:

var chosenFeed : String? 
class About_VC: UIViewController {
   //code here 
}

One last note, from the example pictures you posted be careful with force unwrapping. Cheers!

Upvotes: 1

Related Questions