gpt4 book ai didi

swift - 如何在 switch 语句中转至特定情况

转载 作者:行者123 更新时间:2023-11-30 13:27:01 24 4
gpt4 key购买 nike

在第一部分中,我根据行显示不同的样式UIAlertController。第二部分做不相关的事情。为了避免两个 case 中的代码重复,如何在 switch 语句中切换到特定的 case?这可以快速实现吗?其他语言有这个概念吗?

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 的另一个答案中提到的

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 关键字似乎也无法解决问题,因为它不会评估 case 条件:

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
}

关于swift - 如何在 switch 语句中转至特定情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37056400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com