Pattern matching for tuples in Swift allows for convenient comparison and unpacking of values. In a switch statement, you can decompose tuples directly in the pattern:
let point = (x: 0, y: 2) switch point { case (0, 0): print("At the origin") case (0, let y): print("x = 0, y = \(y)") case let (x, y) where x == y: print("x equals y") default: print("Another point") }
Nuances:
Can you use a tuple of type
(String, Int)in a switch-case with a case pattern of different types, e.g.,case (let a, let b):?
Often, people respond that it is possible, but it is important — the variable types in the pattern must strictly correspond to the tuple type.
let pair = ("abc", 5) switch pair { case (let text, let number): print("String: \(text), number: \(number)") // Ok case (let x, let y) where x == y: print("Error") // Error: Binary operator '==' cannot be applied to operands of type 'String' and 'Int' default: break }
If the types do not match, the compiler will produce an error at compile time.
Story
In one project, we tried to use switch-case to parse the server response as a tuple without considering the possibility of nil values. This resulted in no case matching, and the default was triggered, although another logic was intended.
Story
Type mismatch: in the tuple handler function, we received (Int, String), but tried to unpack it as (String, Int). The result — a crash at compile time and lost time searching for the cause.
Story
We used guard to unpack the result tuple without considering the case with negative values, although processing was intended only for positive numbers. As a result, some valid cases were ignored, which turned out to be a problem in the business logic.