Pattern matching is a powerful feature in Swift that allows you to match and extract values from data structures like arrays, tuples, and enums. It is used in switch statements, if case statements, and for loops to provide concise and expressive code for handling different cases efficiently. Let's explore how to work with pattern matching in Swift.
let name = "Alice"
switch name {
case "Alice":
print("Hello, Alice!")
case "Bob":
print("Hello, Bob!")
default:
print("Hello, stranger!")
}
In this example, we use a switch statement with pattern matching to check the value of the variable `name` and print a corresponding message based on the match.
let point = (x: 3, y: 4)
if case (3, 4) = point {
print("Point is at (3, 4)")
}
Here, we use an if case statement with pattern matching to check if the variable `point` matches the tuple `(3, 4)`.
let coordinates = [(1, 2), (3, 4), (5, 6)]
for case let (x, y) in coordinates {
print("x: \(x), y: \(y)")
}
In this example, we use a for loop with pattern matching to extract and print the `x` and `y` values from each tuple in the `coordinates` array.