0
0
Swiftprogramming~5 mins

No implicit fallthrough in switch in Swift

Choose your learning style9 modes available
Introduction

Swift's switch statements do not automatically continue to the next case. This helps avoid mistakes where code runs in cases you don't want.

When you want to check a value and run code only for the matching case.
When you want to make sure each case is handled clearly without accidental overlap.
When you want safer and easier-to-read code that avoids bugs from running extra cases.
When you want to use switch to replace multiple if-else statements cleanly.
Syntax
Swift
switch value {
case pattern1:
    // code for pattern1
case pattern2:
    // code for pattern2
default:
    // code if no other case matches
}

Each case must end without automatically running the next case.

If you want to run code in multiple cases, list them separated by commas.

Examples
This checks the number and prints the matching case only.
Swift
let number = 2
switch number {
case 1:
    print("One")
case 2:
    print("Two")
case 3:
    print("Three")
default:
    print("Other number")
}
This groups multiple cases together to print "Vowel" if letter is any vowel.
Swift
let letter = "a"
switch letter {
case "a", "e", "i", "o", "u":
    print("Vowel")
default:
    print("Consonant")
}
Each case runs only its own code, no accidental fallthrough.
Swift
let day = 3
switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
// No fallthrough to next case
default:
    print("Another day")
}
Sample Program

This program prints a message based on the grade. Only the matching case runs.

Swift
let grade = "B"
switch grade {
case "A":
    print("Excellent!")
case "B":
    print("Good job!")
case "C":
    print("You passed.")
default:
    print("Try harder next time.")
}
OutputSuccess
Important Notes

Unlike some languages, Swift does not let cases fall through automatically.

If you want to run code in the next case, you must use the fallthrough keyword explicitly.

This design helps prevent bugs and makes your code clearer.

Summary

Swift switch cases do not run into each other automatically.

You must write code for each case separately or use fallthrough if needed.

This makes your code safer and easier to understand.