0

UIAlertController最初のセクションでは、行に基づいて異なるスタイルを示します。2 番目のセクションでは、無関係なことを行います。両方の s でコードの重複を避けるために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
    }
}
4

2 に答える 2

1

あなたが現在達成しようとしていることは、Swiftswitchステートメントでは不可能なようです。@AMomchilovによる別の回答で述べたように

デフォルトでは、Swift の switch ステートメントは、各ケースの最下部から次のケースに移行しません。代わりに、明示的な break ステートメントを必要とせずに、最初に一致する switch ケースが完了するとすぐに、switch ステートメント全体が実行を終了します。

ケース条件を評価しないため、fallthroughキーワードも問題を解決していないようです。

フォールスルー ステートメントは、switch ステートメント内の 1 つのケースから次のケースへとプログラムの実行を継続させます。case ラベルのパターンが switch ステートメントの制御式の値と一致しない場合でも、プログラムの実行は次のケースに進みます。

最善の解決策は、次のようなものを持つことだと思います

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 ステートメントは、デフォルトでは、各ケースの最下部から次のケースに移行しません。代わりに、明示的な break ステートメントを必要とせずに、最初に一致する switch ケースが完了するとすぐに、switch ステートメント全体が実行を終了します。これにより、switch ステートメントは C のステートメントよりも安全で使いやすくなり、誤って複数の switch ケースを実行することを回避できます。- Swift プログラミング言語 (Swift 2.2) - 制御フロー

ただし、フォールスルー キーワードは、機能を追加するためにのみ使用できます。1 番目と 2 番目のケースを相互に排他的にして、3 番目のケースにフォールスルーすることはできません。あなたの状況では、switch ステートメントの後に無条件に発生する一般的なケースをリファクタリングし、デフォルトのケースを からbreakに変更しますreturn

于 2016-05-05T17:18:05.000 に答える