如何在 switch 语句中跳转到特定情况

How to fallthrough to a specific case in switch statement

在我的第一部分中,我根据行展示了不同的样式 UIAlertController。第二部分做不相关的事情。为了避免两个 case 中的代码重复,我如何在 switch 语句中跳转到特定情况?这在 swift 中可能吗?其他语言有这个概念吗?

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
    }
}

您使用了 fallthrough 关键字。

No Implicit Fallthrough

In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit break statement. This makes the switch statement safer and easier to use than the one in C and avoids executing more than one switch case by mistake. -The Swift Programming Language (Swift 2.2) - Control Flow

但是,fallthrough 关键字只能用于添加功能。你不能让第一种情况和第二种情况相互排斥,并且还落入第三种情况。在您的情况下,会将常见情况重构为在 switch 语句之后无条件发生,并将默认情况从 break 更改为 return.

Swift switch 语句似乎无法实现您目前想要实现的目标。正如@AMomchilov

在另一个回答中提到的

switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit break statement.

fallthrough 关键字似乎也没有解决问题,因为它不会评估大小写条件:

A fallthrough statement causes program execution to continue from one case in a switch statement to the next case. Program execution continues to the next case even if the patterns of the case label do not match the value of the switch statement’s control expression.

我认为最好的解决方案是

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
}