Swift Fallthrough Statement
The Swift fallthrough statement makes the statements after a case continue to run in sequence, and they execute regardless of whether the condition is met.
A switch in Swift does not fall through from one case branch to the next. As soon as the first matching case branch finishes the statements it needs to execute, the entire switch block completes its execution.
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.
Syntax
The syntax 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 的值为 5
Swift Loops