switch

If you care to match multiple patterns, the switch statement is your best friend. You can rewrite processPoint() like this:

func process(point: (x: Int, y: Int, z: Int)) -> String {

// 1

let closeRange = -2...2 let midRange = -5...5

// 2

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

return "At origin"

case (closeRange, closeRange, closeRange): return "Very close to origin"

case (midRange, midRange, midRange): return "Nearby origin"

default:

return "Not near origin"

}

}

let point = (x: 15, y: 5, z: 3)

let response = process(point: point) // Not near origin

This code introduces a couple of new concepts:

  1. You can match against ranges of numbers.
  2. The switch statement allows for multiple cases to match patterns.

The switch statement also provides an advantage over the if statement because of its exhaustiveness checking. The compiler guarantees that you have checked for all possible values by the end of a switch statement.

Also recall that a switch statement will exit with the first case condition that matches. That's why the midRange condition is placed second. Even though the midRange condition would match a closeRange value, it won't be evaluated unless

the previous condition fails. The default case is the catch-all. If there hasn’t been a match in all the other cases, the default case will execute.

results matching ""

    No results matching ""