0
0
Swiftprogramming~5 mins

Why Swift has no implicit fallthrough

Choose your learning style9 modes available
Introduction

Swift does not allow automatic moving from one case to the next in a switch statement to avoid mistakes and make code clearer.

When you want to make sure each choice in a switch is handled clearly and separately.
When you want to avoid bugs caused by accidentally running code for multiple cases.
When you want your code to be easier to read and understand by others.
When you want to write safer programs that catch errors early.
When you want to explicitly decide if one case should continue to the next.
Syntax
Swift
switch value {
case pattern1:
    // code for pattern1
case pattern2:
    // code for pattern2
// no automatic fallthrough
}

Each case must end without automatically continuing to the next.

Use the fallthrough keyword if you want to continue to the next case explicitly.

Examples
This switch checks the number and prints only the matching case.
Swift
let number = 2
switch number {
case 1:
    print("One")
case 2:
    print("Two")
case 3:
    print("Three")
default:
    print("Other")
}
Here, fallthrough makes the code continue from case 2 to case 3.
Swift
let number = 2
switch number {
case 1:
    print("One")
case 2:
    print("Two")
    fallthrough
case 3:
    print("Three")
default:
    print("Other")
}
Sample Program

This program prints the day name for the number. It uses fallthrough to also print the next day.

Swift
let day = 3
switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
    fallthrough
case 4:
    print("Thursday")
default:
    print("Other day")
}
OutputSuccess
Important Notes

Implicit fallthrough can cause bugs if you forget to stop the code from running into the next case.

Swift forces you to be clear and intentional with fallthrough.

This makes your code safer and easier to understand.

Summary

Swift switch statements do not automatically continue to the next case.

You must use fallthrough to move to the next case explicitly.

This helps prevent mistakes and makes code clearer.