0
0
Swiftprogramming~5 mins

Switch with where clauses in Swift

Choose your learning style9 modes available
Introduction

A switch with where clauses lets you check extra conditions for each case. It helps you make decisions based on more detailed rules.

When you want to check a value and also test extra conditions before choosing a case.
When you have multiple cases that depend on both the value and some other property.
When you want to keep your code clean by combining value checks and conditions in one place.
Syntax
Swift
switch value {
case pattern where condition:
    // code to run
case anotherPattern where anotherCondition:
    // code to run
default:
    // code to run if no cases match
}

The where clause adds an extra test to a case.

If the where condition is false, the switch moves to the next case.

Examples
This checks if the number is greater than 5 or not, using where clauses.
Swift
let number = 10

switch number {
case let x where x > 5:
    print("Number is greater than 5")
case let x where x <= 5:
    print("Number is 5 or less")
}
This example compares two numbers in a tuple using where clauses.
Swift
let point = (x: 3, y: 4)

switch point {
case let (x, y) where x == y:
    print("x and y are equal")
case let (x, y) where x > y:
    print("x is bigger")
case let (x, y) where x < y:
    print("y is bigger")
}
Sample Program

This program uses a switch with where clauses to print the age group.

Swift
let age = 20

switch age {
case let a where a < 13:
    print("Child")
case let a where a >= 13 && a < 20:
    print("Teenager")
case let a where a >= 20:
    print("Adult")
}
OutputSuccess
Important Notes

Use let in the case to capture the value for the where condition.

The where clause can use any condition that returns true or false.

Summary

Switch with where clauses lets you add extra checks to each case.

It keeps your code clear by combining pattern matching and conditions.

Use it when you want to test values with more detailed rules.