Swift Fallthrough Statement
The Swift fallthrough statement causes the statements after a case to continue running in order, and they will execute regardless of whether the condition is met.
In Swift, switch does not fall through from one case branch to the next. As soon as the first matching case branch completes its required statements, the entire switch code block finishes its execution.
Note:In most languages, in a switch statement block, each case must be followed by break, otherwise the statements after the case will run sequentially. However, in Swift, by default execution does not continue, and the switch terminates. If you want the statements after a case to continue running sequentially in Swift, you need to use the fallthrough statement.
Syntax
The syntax format of the Swift fallthrough statement is as follows:
fallthrough
Generally, the fallthrough statement is not used in switch statements.
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 Loops