Swift – Fallthrough Statement
Just like other languages in Swift also switch statement is very useful and powerful. It takes a value and then compare it with several possible matching pattern or we can say cases and stops its execution when it successfully found its first matching case statement and then execute the code present in the matched statement. It optimise code by avoiding the repetitive use of if-else statements. In Swift, the switch statement does not fall through the bottom of each case statement. Instead, the switch statement finish its execution when it encounter its first matching case without any explicit break statement. It makes switch statement more safer and easier to use and avoid executing more than one case statement by mistake.
If you want your switch statement fall through or you want C style fallthrough feature then you can use fallthrough statement. This statement is used to forcefully execute the case present next after the matched statement even though the case is not matching the specified condition. Remember it only execute one case statement that present after the matched statement not all the case statements unless the fallthrough statement is used after all the case statements.
In this example, we will first see how the normal switch statement works.
Hi! its Tuesday
Here, we enter condition in the switch statement that is “choice = 2”. Now the switch statement compare the condition with each switch statement one by one and the match found in the second case so it display “Hi! its Tuesday” and stop its execution.
Now we use the same code to see how the fallthrough statement works.
Hi! its Tuesday Hi! its Wednesday
Here, the switch statement(i.e. choice = 2) found its match on case 2, i.e., “Hi! its Tuesday” but it also display “Hi! its Wednesday” after “Hi! its Tuesday” because a fallthrough statement is used just after the statement of case 2. Due to fallthrough statement the case 3 is forcefully executed.
Your today day is going to be very bad Your today day is going to be ok Your today day is going to be full of up and downs Choice not found
Explanation: In this example, we pass the “choice = “Three” condition in the switch statement and we put fallthrough statement after every case statement. So when the switch case found the matching case that is case ” Three” then the case “Three” statement and the cases present after case “Three” will execute due to fallthrough statement.