Advanced Pattern Matching

Tuple Pattern

released Fri, 15 Feb 2019
Swift Version 5.0

Tuple Pattern

We have a full article on tuples, but here is a quick overview:

let age = 23

let job: String? = \"Operator\"

let payload: Any = NSDictionary()



switch (age, job, payload) {

case (let age, _?, _ as NSDictionary):

     print(age)

default: ()

}

Here, we're combining three values into a tuple (imagine they're coming from different API calls) and matching them in one go. Note that the pattern achieves three things:

  1. It extracts the age
  2. It makes sure there is a job, even though we don't need it
  3. It makes sure that the payload is of kind NSDictionary even though we don't need the actual value either.