簡體   English   中英

如何在switch語句中陷入特定情況

[英]How to fallthrough to a specific case in switch statement

在我的第一部分中,我基於行顯示了不同樣式的UIAlertController 第二部分做無關的東西。 為了避免兩種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
    }
}

當前使用Swift switch語句似乎無法實現的目標。 如@AMomchilov的另一個答案中所述

Swift中的switch語句默認不會落入每種情況的底部,而不會落入下一種情況。 相反,整個switch語句將在第一個匹配的switch情況完成后立即完成其執行,而無需顯式的break語句。

fallthrough關鍵字似乎也無法解決問題,因為它不會評估案例條件:

fallthrough語句使程序執行從switch語句中的一種情況繼續到另一種情況。 即使case標簽的模式與switch語句的控制表達式的值不匹配,程序也會繼續執行下一個case。

我認為最好的解決方案是

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
}

您使用fallthrough關鍵字。

沒有隱式掉線

與C和Objective-C中的switch語句相比,Swift中的switch語句不會掉入每種情況的底部,默認情況下不會掉入下一種情況。 相反,整個switch語句將在第一個匹配的switch情況完成后立即完成其執行,而無需顯式的break語句。 這使得switch語句比C語言中的語句更安全,更易於使用,並且避免了錯誤執行多個switch情況。 -Swift編程語言(Swift 2.2)-控制流

但是,fallthrough關鍵字只能用於添加功能。 您不能讓第一種情況和第二種情況互斥,也不能陷入第三種情況。 在您的情況下,可以將普通情況重構為在switch語句后無條件發生,並將默認情況從break更改為return

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM