Understanding Fall-Through Statement
Swift Fallthrough Statement: Understanding Its Role in Switch Cases
What is the Fallthrough Statement in Swift?
In Swift, a switch statement is designed to exit as soon as the first matching case executes, unlike in C and C++, where execution continues to the next case unless explicitly stopped with a break statement.
However, Swift provides a fallthrough
statement that
allows execution to continue to the next case, even if the first
condition is met. While this behavior can be useful in some
scenarios, developers generally avoid it as it may reduce code
readability and lead to unexpected behaviors.
Syntax of Switch Statement in Swift
Below is the general syntax for a switch statement in Swift:
switch expression {
case expression1:
statement(s)
fallthrough
// Optional
case expression2, expression3:
statement(s)
fallthrough
// Optional
default:
// Optional
statement(s)
}
If the fallthrough
statement is omitted, execution will
exit the switch statement after executing the matching case. Let's
explore this concept with examples.
Example 1: Switch Statement Without Fallthrough
This example demonstrates how Swift exits a switch statement after executing the matching case.
import
Foundation
var number = 20
switch number {
case 50:
print("The number is 50")
case 20, 30:
print("The number is either 20 or 30")
case 10:
print("The number is 10")
default:
print("No match found")
}
Output
Since 20 matches a case, the program executes the associated statement and exits the switch.
Example 2: Switch Statement with Fallthrough
Now, let's see how adding fallthrough
affects
execution.
import
Foundation
var number = 20
switch number {
case 50:
print("The number is 50")
fallthrough
case 20, 30:
print("The number is either 20 or 30")
fallthrough
case 10:
print("The number is 10")
default:
print("No match found")
}
Output
The number is 10
Here, because of fallthrough
, execution continues to
the next case, even though it doesn’t match the value.