A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. In Swift, a switch case can contain a temporary let constant, which contains the variable's value.
Although break isn't required in Swift, you can use a break statement to match and ignore a particular case or to break out of a matched case before that case has completed its execution. For details, see Break in a Switch Statement. The body of each case must contain at least one executable statement.
A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases like it happens in C and C++ programing languages.
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 :)
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:
()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With