The switch statement in Swift, as long as the first match (case) completes, not through the bottom of subsequent cases (case), as it does in C and C + + programming languages. The following are common syntax for switch statements in C and C + +:
Copy Code code as follows:
switch (expression) {
Case Constant-expression:
statement (s);
Break * Optional * *
Case Constant-expression:
statement (s);
Break * Optional * *
/* can have any of the case statements * *
Default:/* Optional * *
statement (s);
}
Here, we need to exit the case statement with the break statement, or the execution control will fall to the following case statement that matches the case statement.
Grammar
Here is the general syntax for Swift's switch statement:
Copy Code code as follows:
Switch Expression {
Case expression1:
Statement (s)
Fallthrough/* Optional *
Case Expression2, Expression3:
Statement (s)
Fallthrough/* Optional *
Default:/* Optional * *
statement (s);
}
If you do not use the Fallthrough statement, the program will step back out of the match case statement in the switch statement. We will use the following two examples to illustrate its functionality and usage.
Example 1
Here is an example of not using Fallthrough in the Swift programming switch statement:
Copy Code code as follows:
Import Cocoa
var index = 10
Switch Index {
Case 100:
println ("Value of Index is 100")
Case 10,15:
println ("Value of index is either 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 or 15
Example 2
The following is an example of a switch statement with Fallthrough in Swift programming:
Copy Code code as follows:
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 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 or Value of
index is 5