准备 segue:无法将类型 'UIViewController' 的值转换为指定类型 'SecondViewController'

Prepare for segue: Cannot convert value of type 'UIViewController' to specified type 'SecondViewController'

我知道我一定遗漏了一些明显的东西,但我似乎无法通过它的实际类型来引用目标视图控制器。我按照以下步骤从头开始创建了一个新项目来测试它:

这会导致错误 Cannot convert value of type 'UIViewController' to specified type 'SecondViewController'。我已经尝试了我能想到的一切,尝试了所有的 segue 类型等,但我没有想法。我知道 segue 本身的工作就像我注释掉它确实调用第二个视图控制器的代码一样(我什至在名称中添加了一个标签只是为了确定)。

我是 Swift 和 Storyboard 的新手,所以我在这里可能缺少一些简单的东西,但我们将不胜感激任何帮助!

您应该可以像这样设置值。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if let vc: SecondViewController = segue.destinationViewController as? SecondViewController {
        vc.id = "test"
    }
}

如果您添加其他 segues,这也会更安全。

另一种方法是用

强制施放控制器
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    let vc: SecondViewController = segue.destinationViewController as! SecondViewController
    vc.id = "test"
}

这段代码应该可以编译,但如果使用错误的 destinationViewController 调用它会崩溃,而不是 if let 选项,如果它不是预期的,则不会设置目标控制器的 id 值 class.

在 Swift 中,您可以使用 guard 语句解包 segue.destinationViewController cast

guard let destVC : SecondViewController = segue.destinationViewController as? SecondViewController else {
    return
}
destVC.id = "test"

或者对值不为 nil 的特定类型的 UIViewController 使用条件检查

if let destVC : SecondViewController? = segue.destinationViewController as? SecondViewController where destVC != nil {
    destVC?.id = "test"
    return
}