繁体   English   中英

如何在switch语句中陷入特定情况

[英]How to fallthrough to a specific case in switch statement

在我的第一部分中,我基于行显示了不同样式的UIAlertController 第二部分做无关的东西。 为了避免两种case的代码重复,我如何在switch语句中陷入特定情况? 这可能很快吗? 还有其他语言有这个概念吗?

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    var alertController: UIAlertController!
    let cancelAction = UIAlertAction(title: L10n.Cancel.localized, style: .Cancel) { (action) in
        // ...
    }
    switch (indexPath.section, indexPath.row) {
    case (0, 0):
        alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        //add other actions
    case (0, 1):
        alertController = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)
        //add other actions
    case (0, _): //this case handles indexPath.section == 0 && indexPath.row != 0 or 1
        //I want this to be called too if indexPath.section is 0;
        //even if indexPath.row is 0 or 1.
        alertController.addAction(cancelAction)
        presentViewController(alertController, animated: true, completion: nil)
    default:
        break
    }
}

当前使用Swift switch语句似乎无法实现的目标。 如@AMomchilov的另一个答案中所述

Swift中的switch语句默认不会落入每种情况的底部,而不会落入下一种情况。 相反,整个switch语句将在第一个匹配的switch情况完成后立即完成其执行,而无需显式的break语句。

fallthrough关键字似乎也无法解决问题,因为它不会评估案例条件:

fallthrough语句使程序执行从switch语句中的一种情况继续到另一种情况。 即使case标签的模式与switch语句的控制表达式的值不匹配,程序也会继续执行下一个case。

我认为最好的解决方案是

switch (indexPath.section, indexPath.row) {
case (0, _):
    if indexPath.row == 0 {
        alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
    }
    alertController = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)
    alertController.addAction(cancelAction)
    presentViewController(alertController, animated: true, completion: nil)
default:
    break
}

您使用fallthrough关键字。

没有隐式掉线

与C和Objective-C中的switch语句相比,Swift中的switch语句不会掉入每种情况的底部,默认情况下不会掉入下一种情况。 相反,整个switch语句将在第一个匹配的switch情况完成后立即完成其执行,而无需显式的break语句。 这使得switch语句比C语言中的语句更安全,更易于使用,并且避免了错误执行多个switch情况。 -Swift编程语言(Swift 2.2)-控制流

但是,fallthrough关键字只能用于添加功能。 您不能让第一种情况和第二种情况互斥,也不能陷入第三种情况。 在您的情况下,可以将普通情况重构为在switch语句后无条件发生,并将默认情况从break更改为return

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM