How can I write an empty case in Swift?
SwiftSwift 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:
()
}