0
0
Swiftprogramming~5 mins

Switch with value binding in Swift

Choose your learning style9 modes available
Introduction

Switch with value binding lets you check a value and grab parts of it to use inside the switch cases.

When you want to check a number and also use that number inside the case.
When you have a tuple and want to match some parts while keeping others for use.
When you want to handle different shapes of data and extract details easily.
When you want to write clear code that handles many conditions with values.
Syntax
Swift
switch value {
case let x:
    // use x here
case let (a, b):
    // use a and b here
default:
    // fallback case
}

You use let or var before a name to capture the value.

Value binding lets you use the matched value inside the case block.

Examples
This binds the whole number to x and prints it.
Swift
let number = 5
switch number {
case let x:
    print("Number is \(x)")
}
This binds the tuple parts to x and y and prints them.
Swift
let point = (3, 4)
switch point {
case let (x, y):
    print("Point is at x=\(x), y=\(y)")
}
This matches points on axes and binds the other coordinate.
Swift
let point = (0, 5)
switch point {
case (0, let y):
    print("On the y-axis at \(y)")
case (let x, 0):
    print("On the x-axis at \(x)")
case let (x, y):
    print("At x=\(x), y=\(y)")
}
Sample Program

This program checks where the point is and prints a message using the bound values.

Swift
let coordinate = (2, 0)
switch coordinate {
case (0, let y):
    print("On the y-axis at y = \(y)")
case (let x, 0):
    print("On the x-axis at x = \(x)")
case let (x, y):
    print("At point (\(x), \(y))")
}
OutputSuccess
Important Notes

Value binding helps you avoid repeating the value inside the case.

You can use var instead of let if you want to change the value inside the case.

Summary

Switch with value binding lets you check and use parts of a value easily.

Use let or var to capture values inside cases.

This makes your code clearer and more flexible when handling data.