How can I write an empty case in Swift?

Swift

Swift Problem Overview


Since swift does not fallthrough case statements in switch, How can I write an empty case statement without getting an error?

let a = 50
switch a {
case 0..10:
case 10..100:
    println("between 10 and 100")
default:
    println("100 and above")
}

How can I make the first case stop the switch?

Swift Solutions


Solution 1 - Swift

let a = 50
switch a {
case 0..10:
    break // Break the switch immediately
case 10..100:
    println("between 10 and 100")
default:
    println("100 and above")
}

Keyword break is optional, but not in this case :)

Solution 2 - Swift

To prevent the error:

> Case label in a switch should have at least one executable statement

... use () in case label like in the following example. Also works with default label.

let a = 1
switch a {
case 1:
    ()
case 2:
    println("2")
default:
    ()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBarnashView Question on Stackoverflow
Solution 1 - Swiftuser2742371View Answer on Stackoverflow
Solution 2 - SwiftMarkus RautopuroView Answer on Stackoverflow