Noop for Swift's Exhaustive Switch Statements

后端 未结 5 1616
有刺的猬
有刺的猬 2020-11-30 07:17

Swift requires exhaustive switch statements, and that each case have executable code.

\'case\' label in a \'switch\' should have at least one executable

相关标签:
5条回答
  • 2020-11-30 07:34

    The cleanest solution I've found is to simply include your last statement in the switch case as your default. This avoids the need to add break or other unnecessary statements while still covering all possible cases.

    For example:

    switch myVar {
    
    case 0:
        myOtherVar = "Red"
    
    case 1:
        myOtherVar = "Blue"
    
    default:
        myOtherVar = "Green"
    
    }
    
    0 讨论(0)
  • 2020-11-30 07:45

    According to the book, you need to use break there:

    The scope of each case can’t be empty. As a result, you must include at least one statement following the colon (:) of each case label. Use a single break statement if you don’t intend to execute any code in the body of a matched case.

    0 讨论(0)
  • 2020-11-30 07:54

    You can use a break statement:

    let vegetable = "red pepper"
    var vegetableComment: String = "Nothing"
    switch vegetable {
    case "cucumber", "watercress":
        break // does nothing
    case let x where x.hasSuffix("pepper"):
        vegetableComment = "Is it a spicy \(x)?"
    default:
        vegetableComment = "Everything tastes good in soup."
    }
    

    Example modified from the docs

    0 讨论(0)
  • 2020-11-30 07:57

    Below is one option for null statement, but maybe not a good solution. I cannot find a statement like python pass

    {}() 
    

    for switch case, break is better choice.

    break
    
    0 讨论(0)
  • 2020-11-30 07:57

    In addition to break mentioned in other answers, I have also seen () used as a no-op statement:

    switch 0 == 1 {
    case true:
        break
    case false:
        ()
    }
    

    Use () if you find break confusing or want to save 3 characters.

    0 讨论(0)
提交回复
热议问题