Alek Piasecki Alek Piasecki - 21 days ago 6
Swift Question

How to make prepare for segue specific to one particular segue?

I have a some code set up with a

prepare(for segue:)
being used to pass information from the current tableviewcontroller to the destination one. This prepare for is intended to be used for when any of the cells in the table are selected, however, this is not the only segue from that viewcontroller. There are other segues that come from buttons clicked, but I think the way that I have the information pass set up is generic for any segue... meaning when the button segues are clicked, the way the code is set up the app is expecting to see the the VC from the cell's segue. Since it doesn't the app crashes. How do I set my code so that the prepare for function is not general to any story board segue (as I think it currently is) but instead to specifically the cell segue? Here is the current set up:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow
let rowSelectedd = indexPath
let destViewController: MainPageCellSelectedViewController = segue.destination as! MainPageCellSelectedViewController
destViewController.rowSelected = rowSelectedd!
}
var rowSelectedd = IndexPath()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "cellSelected", sender: rowSelectedd)
}


I believe the problem is (correct me if I'm wrong) in the
for segue: UIStoryboardSegue
not being specific, but I don't know how to set up an identifier there.

Answer

If you configured this correctly, the segue has an identifier for this very purpose. Check the identifier and bow out if it's the wrong one:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard segue.identifier == "cellSelected" else {return}
    // ...
}