Swift switch
Statement
The switch statement allows testing a variable against multiple values. In Swift, once a case is matched, the entire switch statement completes its execution.
Syntax
The syntax for the switch statement in Swift:
switch expression {
case expression1:
statement(s)
fallthrough // Optional
case expression2, expression3:
statement(s)
fallthrough // Optional
default: // Optional
statement(s);
}
The fallthrough
statement is generally not used in switch statements.
It's important to note that if the fallthrough statement is not used in a case, the switch will terminate after executing the current case, and control flow will move to the next line following the switch statement.
If the fallthrough statement is used, it will continue executing the subsequent case or default statements, regardless of whether their conditions are met.
Note: In most languages, a break
statement is required after each case in a switch block to prevent the subsequent cases from executing. However, in Swift, the execution does not continue by default. If you want the case statements to continue executing in Swift, you need to use the fallthrough
statement.
Example 1
The following example does not use the fallthrough
statement:
import Cocoa
var index = 10
switch index {
case 100:
print("index is 100")
case 10, 15:
print("index is 10 or 15")
case 5:
print("index is 5")
default:
print("default case")
}
When the above code is compiled and executed, it produces the following result:
index is 10 or 15
Example 2
The following example uses the fallthrough
statement:
import Cocoa
var index = 10
switch index {
case 100:
print("index is 100")
fallthrough
case 10, 15:
print("index is 10 or 15")
fallthrough
case 5:
print("index is 5")
default:
print("default case")
}
When the above code is compiled and executed, it produces the following result:
index is 10 or 15
index is 5