Push segue from UITableViewCell to ViewController in Swift

Jack picture Jack · Feb 4, 2015 · Viewed 33.7k times · Source

I'm encountering problems with my UITableViewCells. I connected my UITableView to a API to populate my cells.

Then I've created a function which grabs the indexPath.row to identify which JSON-object inside the array that should be sent to the RestaurantViewController.

Link to my Xcode Project for easier debugging and problem-solving

Here's how my small snippet looks for setting the "row-clicks" to a global variable.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     i = indexPath.row
}

And here's my prepareForSegue() function that should hook up my push-segue to the RestaurantViewController.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "toRestaurant"{
    let navigationController = segue.destinationViewController as UINavigationController
    let vc = navigationController.topViewController as RestaurantViewController
    vc.data = currentResponse[i] as NSArray
 }
}

And here's how I've set up my segue from the UITableViewCell

Here's my result, I've tried to click every single one of these cells but I won't be pushed to another viewController...I also don't get an error. What is wrong here?

Tried solutions that won't work

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "toRestaurant"{
            let vc = segue.destinationViewController as RestaurantViewController
            //let vc = navigationController.topViewController as RestaurantViewController
            vc.data = currentResponse[i] as NSArray
        }
    }

Answer

ergoon picture ergoon · Feb 10, 2015

The problem is that you're not handling your data correctly. If you look into your currentResponse Array, you'll see that it holds NSDictionaries but in your prepareForSegue you try to cast a NSDictionary to a NSArray, which will make the app crash.

Change the data variable in RestaurantViewController to a NSDictionary and change your prepareForSegue to pass a a NSDictionary

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if let cell = sender as? UITableViewCell {
        let i = redditListTableView.indexPathForCell(cell)!.row
        if segue.identifier == "toRestaurant" {
            let vc = segue.destinationViewController as RestaurantViewController
            vc.data = currentResponse[i] as NSDictionary
        }
    }
}  

For Swift 5

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if let cell = sender as? UITableViewCell {
            let i = self.tableView.indexPath(for: cell)!.row
            if segue.identifier == "toRestaurant" {
                let vc = segue.destination as! RestaurantViewController
                vc.data = currentResponse[i] as NSDictionary
            }
        }
    }