Swift Fallthrough Statement
The Swift fallthrough statement causes the statements after a case label to be executed in sequence, regardless of the matching condition.
In Swift, a switch does not fall through the bottom of each case and into the next one by default. Once the first matching case is completed, the entire switch block finishes its execution.
Note: In most languages, a switch block will fall through to the next case unless a break is met. In Swift, by default, it does not fall through, and the switch terminates. If you want the statements after a case to be executed in sequence in Swift, you need to use the fallthrough statement.
Syntax
The syntax for the Swift fallthrough statement is as follows:
fallthrough
The fallthrough statement is typically 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 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