0
0
Swiftprogramming~5 mins

Switch with compound cases in Swift

Choose your learning style9 modes available
Introduction

Switch with compound cases lets you check if a value matches any of several options in one place. It keeps your code neat and easy to read.

When you want to run the same code for multiple matching values.
When you have a list of related options that need the same response.
When you want to avoid repeating code for similar cases.
When you want your code to be clear and organized.
When you want to handle multiple conditions in a simple way.
Syntax
Swift
switch value {
case option1, option2, option3:
    // code to run if value matches any option
case option4:
    // code for option4
default:
    // code if no cases match
}

You separate multiple cases with commas in one case line.

The default case runs if no other case matches.

Examples
This checks if the fruit is apple, banana, or orange and prints the same message for all.
Swift
let fruit = "apple"
switch fruit {
case "apple", "banana", "orange":
    print("This is a common fruit.")
case "kiwi":
    print("This is a tropical fruit.")
default:
    print("Unknown fruit.")
}
This groups odd and even numbers in compound cases.
Swift
let number = 3
switch number {
case 1, 3, 5, 7, 9:
    print("Odd number")
case 2, 4, 6, 8, 10:
    print("Even number")
default:
    print("Number out of range")
}
Sample Program

This program checks if the day is a weekend or a weekday using compound cases.

Swift
let day = "Saturday"
switch day {
case "Saturday", "Sunday":
    print("It's the weekend!")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    print("It's a weekday.")
default:
    print("Not a valid day.")
}
OutputSuccess
Important Notes

Compound cases help avoid repeating the same code for similar values.

You can mix compound cases with single cases in the same switch.

Remember to include a default case to handle unexpected values.

Summary

Use commas to list multiple values in one case.

Compound cases make your switch statements cleaner and easier to read.

Always include a default case to cover all possibilities.