In swift, the fallthrough statement is used in switch case to execute case statements which are next to the matched case statements based on our requirements.
Generally in swift, switch-case statements will stop execution whenever the first matching case statement found but if we want to execute multiple case statements in switch case then by using fallthrough keyword we can execute multiple case statements even though not matching with the defined condition.
Following is the syntax of using a swift fallthrough statement in a switch case statement.
switch expression {
case pattern 1:
statements
fallthrough
case pattern 2:
statements
case pattern 3, pattern 4:
statements
fallthrough
default:
statements
}
If you observe above swift fallthrough statement syntax we used fallthrough in multiple switch-case statements to execute case statements which are next to the matched switch-case statements.
Now we will see how to use fallthrough statement in swift programming language with examples.
Following is the simple example using fallthrough in swift switch case statement to execute multiple case statements based on our requirements.
var name = "hello"
switch(name) {
case "hello":
print("Matched record")
fallthrough
case "two":
print("Not matched record but the fallthrough automatically picks next case statement")
default:
print("Default")
}
If you observe above swift fallthrough statement example we defined fallthrough statement in multiple switch-case statements to execute case statements next to the matched case statements.
When we run above fallthrough statement example in swift playground we will get a result like as shown below.
Matched record
Not matched record but the fallthrough automatically picks next case statement
This is how we can use fallthrough statements in swift programming language to execute case statements next to matched case statements based on our requirements.