部分匹配

Switch 语句使用部分匹配。

let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 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")
}
  1. 精确匹配值为(0,0,0)的情况。这是 3D 空间的起源。
  2. 匹配 y = 0,z = 0 和 x 的任何值。这意味着坐标位于 x 轴上。
  3. 匹配 x = 0,z = 0 和 y 的任何值。这意味着坐标位于轴上。
  4. 匹配 x = 0,y = 0 和 z 的任何值。这意味着坐标位于 z 轴上。
  5. 匹配其余坐标。

注意:使用下划线表示你不关心该值。

如果你不想忽略该值,则可以在 switch 语句中使用它,如下所示:

let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 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, let y, let z):
  print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}

这里,轴情况使用 let 语法来提取相关值。然后代码使用字符串插值打印值以构建字符串。

注意:此 switch 语句中不需要默认值。这是因为最终的情况基本上是默认的 - 它匹配任何东西,因为元组的任何部分都没有约束。如果 switch 语句耗尽所有可能的值及其大小写,则不需要默认值。

我们还可以使用 let-where 语法来匹配更复杂的情况。例如:

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

switch (coordinates) {
case (let x, let y, _) where y == x:
  print("Along the y = x line.")
case (let x, let y, _) where y == x * x:
  print("Along the y = x^2 line.")
default:
break
}

在这里,我们匹配“y 等于 x”和“y 等于 x 平方”的行。