0
0
Swiftprogramming~3 mins

Why Switch with compound cases in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could handle many choices with just one simple line of code?

The Scenario

Imagine you have a list of fruits and you want to perform the same action for several types like apples, pears, and peaches. Without compound cases, you would write separate code blocks for each fruit.

The Problem

This manual way means repeating the same code many times, making your program longer and harder to read. If you want to change the action, you must update it in many places, which can cause mistakes.

The Solution

Using switch with compound cases lets you group multiple values together in one case. This way, you write the action once, and it applies to all those values, making your code shorter, cleaner, and easier to maintain.

Before vs After
Before
switch fruit {
case "apple":
    print("This is a fruit we like.")
case "pear":
    print("This is a fruit we like.")
case "peach":
    print("This is a fruit we like.")
default:
    print("Unknown fruit.")
}
After
switch fruit {
case "apple", "pear", "peach":
    print("This is a fruit we like.")
default:
    print("Unknown fruit.")
}
What It Enables

This lets you handle many similar cases together easily, saving time and reducing errors.

Real Life Example

Think about a traffic light system where red and yellow mean stop or caution, and green means go. Using compound cases, you can group red and yellow together to trigger the same response.

Key Takeaways

Manual repetition makes code long and error-prone.

Compound cases group multiple values in one case.

Code becomes cleaner, shorter, and easier to update.