1

I have segues going to two different ViewControllers, Detail & Search. The segues going to Detail are working fine, but the one going to Search keeps crashing the app. I have spent two hours reading similar questions but none of them seem to have the same issue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let detailVC = segue.destination as! DetailViewController

    if segue.identifier == "newDocSegue"   {
        // Create a new document and pass it to the detail view.
        detailVC.doc = Document()
        detailVC.isAddAction = true
    }

    if segue.identifier == "editDocSegue"    {
        // Load the existing document into the detail view, for editing.
        let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
        detailVC.doc = Document[indexPath.row]
        detailVC.isAddAction = false
    }
     else if segue.identifier == "searchSegue" {
        shouldPerformSegue(withIdentifier: "searchSegue", sender: Any?.self)
    }

}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
orange-oc
  • 25
  • 7

2 Answers2

3

Your problem is the

let detailVC = segue.destination as! DetailViewController

line. This will attempt to cast any VC (including your search VC) as a DetailViewController. Try this:

let detailVC : UIViewController

if segue.identifier == "newDocSegue"   {
    // Create a new document and pass it to the detail view.
    detailVC = segue.destination as! DetailViewController
    detailVC.doc = Document()
    detailVC.isAddAction = true
}

if segue.identifier == "editDocSegue"    {
    // Load the existing document into the detail view, for editing.
    detailVC = segue.destination as! ???  // not sure what type you want here
    let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
    detailVC.doc = Document[indexPath.row]
    detailVC.isAddAction = false
}
 else if segue.identifier == "searchSegue" {
    detailVC = segue.destination as! SearchViewController
    shouldPerformSegue(withIdentifier: "searchSegue", sender: Any?.self)
}
dylanthelion
  • 1,760
  • 15
  • 23
0

Your problem is at:

let detailVC = segue.destination as! DetailViewController

if your destination's type is SearchViewController cast will cause error

Try this:

if let detailVC = segue.destination as? DetailViewController

You should be aware about as? and as!

sazzad
  • 5,740
  • 6
  • 25
  • 42