Swift - Switches on tuple values


You can do partial matches to the tuple's components:


let switchingTuple = ("Yes", 123) 
switch switchingTuple { 
case ("Yes", 123): 
    print("Tuple contains  'Yes' and  '123'") 
case ("Yes", _): 
    print("Tuple contains  'Yes' and something else") 
case (let string, _): 
    print("Tuple contains the string  '\(string)' and something else") 


The underscore is a wildcard.

The second case matches all tuples that have the string 'Yes'.

The variable declaration inside the third case statement captures the value of the string component of the tuple inside a variable called string.

It matches all tuples regardless of their string value and store that inside this new variable called string.

The switch statement above doesn't have a default case because the last case will catch every possible tuple.

When writing a tuple switch you'll require a default case.

Related Topic