首页 > 解决方案 > Using a ViewController variable in segue.destination

问题描述

In the code below, I'm trying to use the variable controller to fill in the type of my destination segue at the bottom. But instead I get an error message that says controller is undeclared. It's declared right there on the second line! I can see it! I realize there are many alternatives to using segue identifiers but I'm more interested in learning why this doesn't work.

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

    switch segue.identifier {
    case "ASegue":
        controller = AViewController()
    case "BSegue":
        controller = BViewController()
    case "CSegue":
        controller = CViewController()
    default:
        controller = AViewController()
    }

    if let vc = segue.destination as? controller { //Use of undeclared type 'controller'
        ...
    }
}

标签: swiftsegueviewcontroller

解决方案


强制转换必须是类型(文字),而不是变量

controller并且在任何情况下,您都不能像您想要的那样将所有操作合并到一个变量中,这正是因为它们不同的类型。

因此,您只需将转换移动到开关的每个案例中,转换为您期望该 segue 的目标控制器的类型,并在这种 情况下对其进行适当的工作:controller

switch segue.identifier {
case "ASegue":
    if let controller = segue.destination as? AViewController {
        // do stuff
    }
case "BSegue":
    if let controller = segue.destination as? BViewController {
// etc.

如果每个可能的 segue 都有不同的视图控制器类,也许一种更简洁的表达方式是忘记标识符并只使用视图控制器类:

switch segue.destination {
case let controller as AViewController:
    // populate controller
case let controller as BViewController:
    // populate controller
// etc.

推荐阅读