Search code examples
swiftuitableviewsegue

Get index of selected row to use in prepare for segue


I want to pass different arrays from one ViewController to another based on which row is selected.
How can I get the index for selected row?
I have tried this, but it does not work:

let toDetailVCSegue = "ToDetailVCSegue"

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: toDetailVCSegue, sender: indexPath)
    }



     func prepare(for segue: UIStoryboardSegue, sender: IndexPath?)
    {
        if segue.identifier == toDetailVCSegue
        {
        let destination = segue.destination as! DetailViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                if indexPath.row == 0 {
                    destination.itemArray = namesArray
                    print("test")
                }
                if indexPath.row == 1 {
                    destination.itemArray = scoresArray
                }
                if indexPath.row == 2 {
                    destination.itemArray = timesArray
                }
                if indexPath.row == 3 {
                    destination.itemArray = completedArray
                }

            }
        }
    } 

Solution

  • You must not change the signature of prepare(for otherwise it's not going to be called. The sender parameter must be Any?

    Cast the sender parameter to IndexPath and I recommend a switch statement

    func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == toDetailVCSegue {
            let destination = segue.destination as! DetailViewController
            let indexPath = sender as! IndexPath
            switch indexPath.row {
              case 0: destination.itemArray = namesArray
              case 1: destination.itemArray = scoresArray
              case 2: destination.itemArray = timesArray             
              case 3: destination.itemArray = completedArray
              default: break
            }
        }
    }