Partial matching

Another way you can use switch statements with matching to great effect is as follows:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates { case (0, 0, 0): // 1

print("Origin") case (_, 0, 0): // 2

print("On the x-axis.") case (0, _, 0): // 3

print("On the y-axis.") case (0, 0, _): // 4

print("On the z-axis.") default: // 5

print("Somewhere in space")

}

This switch statement makes use of partial matching. Here’s what each case does, in order:

  1. Matches precisely the case where the value is (0, 0, 0). This is the origin of 3D space.
  2. Matches y=0, z=0 and any value of x. This means the coordinate is on the x- axis.
  3. Matches x=0, z=0 and any value of y. This means the coordinate is on the y- axis.
  4. Matches x=0, y=0 and any value of z. This means the coordinate is on the z- axis.
  5. Matches the remainder of coordinates.

You’re using the underscore to mean that you don’t care about the value. If you don’t want to ignore the value, then you can bind it and use it in your switch statement, like this:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates { case (0, 0, 0):

print("Origin") case (let x, 0, 0):

print("On the x-axis at x = (x)") case (0, let y, 0):

print("On the y-axis at y = (y)") case (0, 0, let z):

print("On the z-axis at z = (z)") case let (x, y, z):

print("Somewhere in space at x = (x), y = (y), z = (z)")

}

Here, the axis cases use the let syntax to pull out the pertinent values. The code then prints the values using string interpolation to build the string.

Notice how you don’t need a default in this switch statement. This is because the final case is essentially the default; it matches anything, because there are no constraints on any part of the tuple. If the switch statement exhausts all possible values with its cases, then no default is necessary.

Also notice how you could use a single let to bind all values of the tuple: let (x, y, z) is the same as (let x, let y, let z).

Finally, you can use the same let-where syntax you saw earlier to match more complex cases. For example:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {

case let (x, y, _) where y == x: print("Along the y = x line.")

case let (x, y, _) where y == x * x: print("Along the y = x^2 line.")

default: break

}

Here, you match the “y equals x” and “y equals x squared” lines. And those are the basics of switch statements!

results matching ""

    No results matching ""