Xcode Segue"无法转换类型"

时间:2017-02-13 06:58:25

标签: ios swift xcode

我有两个不同的ViewControllers,细节&搜索。转到详细信息的segues工作正常,但进入搜索的人不断崩溃应用程序。我花了两个小时阅读类似的问题,但似乎没有一个问题有同样的问题:

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)
    }

}

2 个答案:

答案 0 :(得分:1)

你的问题是

让detailVC = segue.destination为! DetailViewController

线。这将尝试将任何VC(包括您的搜索VC)转换为DetailViewController。试试这个:

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)
}

答案 1 :(得分:0)

您的问题出在:

let detailVC = segue.destination as! DetailViewController

如果目的地的类型为SearchViewController,则会导致错误

试试这个:

if let detailVC = segue.destination as? DetailViewController

您应该了解as?as!