Noop for Swift's Exhaustive Switch Statements

后端 未结 5 1633
有刺的猬
有刺的猬 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: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

提交回复
热议问题