In this tutorial you will learn about the Swift Fallthrough Statement and its application with practical example.
Swift Fallthrough Statement
In Swift, the switch statement generally executes only the matching block, and then execution come at the end of the switch statement. Unlike many other programming languages there is no need of break keyword to stop the execution. Look at the below general syntax of a switch statement in other programming languages –
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 |
switch(variable) { case 1: //do something break; case 2: //do something break; default: //do something break; } |
Here, the switch statement generally executes only the matching block, and then execution come at the end of the switch statement as soon as it find break keyword. But, if we omit the break keywords from the cases,then all of the subsequent cases after the matching case will be executed additionally. This execution of additional cases is termed as the “fall through” behavior of switch statement.
The switch statement in swift generally executes only the matching block, and then execution come at the end of the switch statement. Look at the below general syntax of a switch statement in swift –
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 |
switch expression { case val1: statement(s) fallthrough /* optional */ case val2, val3: statement(s) fallthrough /* optional */ default : /* Optional */ statement(s); } |
In Swift, the fallthrough keyword allows to execute all the following statements after a matching block found.
Switch without fallthrough
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
var counter:Int = 25 print("W3Adda - Switch Statement without fallthrough") switch counter { case 75 : print( "Value of counter is 75") case 25,50 : print( "Value of counter is either 25 or 50") case 100 : print( "Value of counter is 100") default : print( "default case") } |
Output:-
Switch with fallthrough
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var counter:Int = 25 print("W3Adda - Switch Statement with fallthrough") switch counter { case 75 : print( "Value of counter is 75") fallthrough case 25,50 : print( "Value of counter is either 25 or 50") fallthrough case 100 : print( "Value of counter is 100") default : print( "default case") } |
Output:-