部分匹配

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 平方”的行。