swift - 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'
...
}
}
解决方案
强制转换必须是类型(文字),而不是变量。
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.
推荐阅读
- python - Python - 尝试从输入中减去时间(不支持的操作数类型)
- python - 无法合并对象列类型上的两个数据框集
- git - 检查分支创建历史
- javascript - 如何使用反应组件创建模块并使用反应惰性加载?
- laravel - 为什么facebook社交名流登录突然不起作用?
- javascript - 如何在动态添加的表单字段上实现先前声明的 jquery.validate 规则
- azure - 为什么 Azure ASP(应用服务计划)手动扩展太慢?
- typescript - 在类型定义文件中定义类型与在普通类型文件中定义类型的好处
- c - 如何使用数组来查找 C 中的最小值(可能还有最大值?)?
- r - 使用 scale_x_datetime 和 geom_col 移动 x 轴刻度,因此条形不会以刻度线为中心