Swift:PrepareForSegue,Swift Cast失败

我想在TableViewController选择一个单元格。 单元格的文本应通过segue传输到FirstViewController的标签。 我总是得到如下所示的错误。

标识符是正确的。

我的代码:

 override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "BackToCalculator") { //let myRow = tableView.indexPathForSelectedRow().row+1 let vc = segue.destinationViewController as FirstViewController vc.SelectedBundesland.text = "Test" } } 

例外:

0x103f1f5dc:jne 0x103f1f5d0; swift_dynamicCastClassUnconditional + 48 0x103f1f5de:leaq 0x3364d(%rip),%rax; “Swift动态强制转换失败”0x103f1f5e5:movq%rax,0xa456c(%rip); gCRAnnotations + 8 0x103f1f5ec:int3
0x103f1f5ed:movq%r14,%rax

哪里不对?

可能会在游戏中迟到但却得到完全相同的问题。 这里的问题是你的Segue指向Tab控制器,而不是它需要跳转到的实际ViewController。 我指的是你提供给Antonio的第二个截图。 如果你修复它应该工作正常。

一种更加安全和前瞻性的方法是条件转换,甚至更好的基于协议,请考虑以下内容:

 override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if let vc = segue.destinationViewController as? FirstViewController { vc.SelectedBundesland.text = "Test" } else { print("Some other controller! \(segue.destinationViewController)") } } 

这肯定有效。 但是如果你有多个segues和多个viewController,摆动信息和数据可能会非常痛苦。

考虑协议方法:

 protocol BundeslandProtocol { var SelectedBundesland: String {get set} } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if var vc = segue.destinationViewController as? BundeslandProtocol { vc.SelectedBundesland.text = "Test" } } 

要完成上述工作,您只需要声明您的UIViewController符合所述协议:

 class AwesomeViewController: UIViewController, BundeslandProtocol { .... } 

随着时间的推移,您将能够重命名您的类,更改它们,替换和扩展您的项目,并且只要协议保持其目的,您就不必关心更改引用。

要告诉代码被破坏的地方并不容易:它通常发生在您忘记在故事板中设置类名(在您的情况下为FirstViewController)中,对于执行segue的控制器,请参见屏幕截图,必须设置而不是UIViewControllergenerics类。

看截图

我有一个类似的错误 – 我相信segue.destinationViewController在这里是一个UINavigationController 。 您收到错误是因为您正在尝试将UINavigationController转换为FirstViewController类。

改变这一行: let vc = segue.destinationViewController as FirstViewController

对此: let vc = segue.destinationViewController.topViewController as FirstViewController

.topViewController是导航堆栈上的顶视图控制器 – 现在应该是FirstViewController一个实例

检查你的故事板,我认为你错误地让segue“指向”另一个viewController。

尝试这个,

 self.performSegueWithIdentifier("BackToCalculator", sender: self) override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "BackToCalculator") { //let myRow = tableView.indexPathForSelectedRow().row+1 let vc = segue.destinationViewController as FirstViewController vc.SelectedBundesland.text = "Test" } 

你需要调用self.performSegueWithIdentifier。