0

在我的第一部分中,我UIAlertController根据行展示了不同的样式。第二部分做不相关的事情。为了避免两个cases 中的代码重复,如何在 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
    }
}
4

2 回答 2

1

What you are trying to achieve currently doesn't seem to be possible with Swift switch statements. As mentioned in another answer by @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.

The fallthrough keyword also doesn't seem to solve the problem, since it won't evaluate the case conditions:

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.

I think that the best solution would be to have something like

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
}
于 2016-05-05T18:25:36.880 回答
-1

您使用fallthrough关键字。

没有隐式失败

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

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

于 2016-05-05T17:18:05.000 回答