Introduction
Switch with value binding lets you check a value and grab parts of it to use inside the switch cases.
Switch with value binding lets you check a value and grab parts of it to use inside the switch cases.
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.
x and prints it.let number = 5 switch number { case let x: print("Number is \(x)") }
x and y and prints them.let point = (3, 4) switch point { case let (x, y): print("Point is at x=\(x), y=\(y)") }
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)") }
This program checks where the point is and prints a message using the bound values.
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))") }
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.
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.
switch statement allow you to do in Swift?let or var before a variable name in the case pattern, like case let x:.let followed by a variable name correctly.let point = (3, 0)
switch point {
case let (x, 0):
print("On the x-axis at \(x)")
case let (0, y):
print("On the y-axis at \(y)")
default:
print("Somewhere else")
}case let (x, 0):, it prints "On the x-axis at 3".let number = 5
switch number {
case let x where x > 0:
print("Positive")
case let x where x < 0:
print("Negative")
case x == 0:
print("Zero")
}case x == 0:, which is not valid pattern syntax in Swift.case let x where x == 0:.let numbers: [Int?] = [3, nil, 7, nil, 1]
for number in numbers {
switch number {
case let x:
print(x)
case nil:
print("No value")
}
}case let x: matches all values including nil, so case nil: is never reached.case let x?: to match only non-nil values and bind them, and case nil: to match nil explicitly.Pass the test and this pattern moves unknown