swift
  1. swift-fallthrough-statement

Swift Fallthrough Statement

In Swift, the fallthrough statement is used to transfer control to the next case block in a switch statement, even if that block’s condition is not met. This is a useful feature when you want to execute code in multiple cases of a switch statement.

Syntax

Here is the syntax for using fallthrough in a switch statement:

switch someValue {
case value1:
    // do something
    fallthrough
case value2:
    // do something else
default:
    // do something by default
}

Example

Here is an example of using fallthrough in a switch statement:

let someValue = 2

switch someValue {
case 1:
    print("Value is 1")
    fallthrough
case 2:
    print("Value is 2")
case 3:
    print("Value is 3")
default:
    print("Value is not between 1 and 3")
}

Output

The output of this code will be:

Value is 2

Explanation

In this example, the switch statement checks for the value of someValue. When someValue is 2, the print("Value is 2") statement is executed. Since the fallthrough keyword is used, control is then transferred to the next case block, which is case 3. However, since someValue is not 3, the print("Value is 3") statement is not executed.

Use

The fallthrough statement is used when you want to execute the code in multiple cases of a switch statement. By default, when a case block is executed, control exits the switch statement. However, if you use the fallthrough keyword, control is transferred to the next case block, even if that block’s condition is not met.

Important Points

  • The fallthrough statement is used to transfer control to the next case block in a switch statement
  • Control is transferred even if the condition for that block is not met
  • The fallthrough keyword is used to indicate that control should be transferred
  • Without the fallthrough keyword, control exits the switch statement after a case block is executed

Summary

The fallthrough statement is a useful feature in Swift for executing code in multiple cases of a switch statement. By using the fallthrough keyword, you can transfer control to the next case block, even if that block’s condition is not met. This can help to reduce code duplication and make your code more efficient and streamlined.

Published on: