In my first section I show different style UIAlertController
based on the row. Second section does unrelated stuff. In order to avoid code duplication in both case
s, how do I fallthrough to a specific case in switch statement? Is this possible in swift? Does any other language have this concept?
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
}
}
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
}