On the use of switch and fallthrough statements in Swift programming
- 2020-05-14 05:01:46
- OfStack
The switch statement in Swift is executed as long as the first matching case (case) is completed, not through the bottom of the subsequent case (case), as it is in C and C++ programming languages. Here is the general syntax for C and C++ switch statements:
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);
}
In this case, we need to exit the case statement using the break statement, otherwise the execution control will all fall below to provide the case statement that matches the case statement.
grammar
Here is the general 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 steps back from the switch statement that matches the case statement. We will use the following two examples to illustrate their functionality and usage.
Example 1
Here is an example of Swift programming switch statements that do not use fallthrough 1:
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
Here is an example of an 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