Noop for Swift's Exhaustive Switch Statements
Solution 1:
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.
Solution 2:
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
Solution 3:
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
Solution 4:
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.
Solution 5:
Do nothing in exhaustive switch case statements:
Swift:
switch yourVariable {
case .someCase:
break
}
SwiftUI:
switch yourVariable {
case .someCase:
EmptyView() // break does not work with ViewBuilder
}
Using EmptyView() instead of break in SwiftUI views prevents the error:
Closure containing control flow statement cannot be used with function builder ViewBuilder.
EmptyView() is a SwiftUI standard view (tested with Xcode 12, iOS 14) and does not need to be defined yourself.