Swift switch Statement
switch The switch statement allows testing whether a variable equals any of several values. In Swift, as soon as a case matches, the entire switch statement finishes executing.
Syntax
The syntax of a switch statement in Swift:
switch expression {
case expression1 :
statement(s)
fallthrough /* 可选 */
case expression2, expression3 :
statement(s)
fallthrough /* 可选 */
default : /* 可选 */
statement(s);
}
Generally, the fallthrough statement is not used in switch statements.
Here we should note that if a case does not use a fallthrough statement, then after the current case executes, the switch terminates and control flow jumps to the line following the switch statement.
If afallthrough statement is used, execution continues with the following case or default statements, whether or not their conditions are met.
Note:In most languages, a case in a switch block must be followed by break, otherwise the statements after the case run sequentially; in Swift, by default execution does not continue and the switch terminates. If you want the statements after a case to continue running in sequence 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 的值为 100")
case 10,15 :
print( "index 的值为 10 或 15")
case 5 :
print( "index 的值为 5")
default :
print( "默认 case")
}
When the above code is compiled and executed, it produces the following result:
index 的值为 10 或 15
Example 2
The following example uses the fallthrough statement:
import Cocoa
var index = 10
switch index {
case 100 :
print( "index 的值为 100")
fallthrough
case 10,15 :
print( "index 的值为 10 或 15")
fallthrough
case 5 :
print( "index 的值为 5")
default :
print( "默认 case")
}
When the above code is compiled and executed, it produces the following result:
index 的值为 10 或 15
index 的值为 5
Swift Conditional Statements