In Swift, the switch statement is executed as long as the first match case completes execution, rather than through the bottom of the subsequent case, as it does in the C and C++ programming languages. Here is the common syntax for switch statements in C and C++:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Here, we need to use the break statement to exit the case statement, otherwise the execution control will fall below to provide the case statement that matches the case statement and then follows.
grammar
The following is the common syntax for Swift's switch statement:
switch expression {
case expression1 :
statement(s)
fallthrough /* optional */
case expression2, expression3 :
statement(s)
fallthrough /* optional */
default : /* Optional */
statement(s);
}
If the fallthrough statement is not used, the program exits after the switch statement executes the matching case statement. We will use the following two examples to illustrate their functionality and usage.
Example 1
The following is an example of not using fallthrough in Swift programming switch statements:
import Cocoa
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
case 10,15 :
println( "Value of index is either 10 or 15")
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
When the above code is compiled and executed, it produces the following results:
Value of index is either 10 or 15
Example 2
The following is an example of a switch statement with fallthrough in Swift programming:
import Cocoa
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
fallthrough
case 10,15 :
println( "Value of index is either 10 or 15")
fallthrough
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
When the above code is compiled and executed, it produces the following results:
Value of index is either 10 or 15 Value of index is 5