当我们在具有多个segues的prepareForSegue:sender:
子类中实现UIViewController
方法时,Objective-C中的一个习惯用法是在storyboard中为segue分配一个标识符,并将逻辑包装在{在prepareForSegue:sender:
语句中{1}}检查segue if
。例如:
identifier
在Swift中,我们基本上被API强制在获取目标视图控制器的实例时使用类型转换。由于这可能会优雅地失败,我的问题是我们应该继续使用条件类型转换(if segue.identifier == "destinationA"
// prepare destinationA stuff
else if segue.identifier == "destinationB"
// prepare destinationB stuff
...
)的可选绑定还是我们还应该依赖as?
语句?
例如,在可能的情况下,我们是否应该赞成仅依靠类型转换的简洁性:
if
或者像在Objective-C中那样将所有内容包装在override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destination = segue.destinationViewController as? DestinationAController {
// prepare stuff for Destination A
} else if let destination = segue.destinationViewController as? DestinationBController {
// prepare stuff for Destination B
}
}
语句中是否有好处:
if
注意:我意识到可以使用开关,但这不是重点。
答案 0 :(得分:1)
依赖于标识符的好处是,如果您的源/目标视图控制器已更改为另一个类,您可以更容易地捕获它,因为它将落入正确的标识符存储桶但无法进行向下转换。严格来说,代码路径不一样。随着更简洁的风格,失败的案件将在所有垂头丧气之后才会被捕获。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "destinationA" {
if let destination = segue.destinationViewController as? DestinationAController {
// prepare stuff for Destination A
}
else {
print("Something is wrong with the controller for destination A!")
}
} else if segue.identifier == "destinationB" {
if let destination = segue.destinationViewController as? DestinationBController {
// prepare stuff for Destination B
}
}
}
VS
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destination = segue.destinationViewController as? DestinationAController {
// prepare stuff for Destination A
} else if let destination = segue.destinationViewController as? DestinationBController {
// prepare stuff for Destination B
}
else {
print("Something is wrong with the controller!")
}
}
另一个好处是,您可以在标识符测试之后和执行向下转换之前执行其他逻辑。
在意图方面使用标识符读取代码也更快 - 不仅更短,标识符是一个Swift字符串,可以说是非常具有描述性。