Swift switch statement
switchThe switch statement allows a variable to be tested for equality against multiple values. In Swift, as long as a case statement is matched, the entire switch statement completes execution.
Syntax
The syntax of a switch statement in Swift is:
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 need to note that if the case statement does not use thefallthroughstatement, then after executing the current case statement, the switch terminates, and control flow jumps to the next line after the switch statement.
If thefallthroughstatement is used, it will continue to execute the following case or default statements, regardless of whether the condition is met.
Note:In most languages, in a switch statement block, case must be followed by break; otherwise, the statements after case will run sequentially. In Swift, by default it will not continue, and the switch also terminates. If you want the statements after case to continue running in order 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 的值为 5Other extensions
Swift conditional statements