Swift Switch 語句

Swift 的 switch 語句比 CJava 中的強大許多。它不僅能匹配整數,還能匹配字串、區間、元組,甚至進行自訂的模式匹配。

基本用法

let fruit = "Apple"

switch fruit {
case "Apple":
    print("是蘋果")
case "Banana", "Orange": // 可以同時匹配多個值
    print("是香蕉或橘子")
default:
    print("不知道是什麼水果")
}

Swift Switch 的特點

  1. 不需要 break:在 C 語言中,每個 case 結束後必須寫 break,否則會繼續執行下一個 case (Fallthrough)。Swift 預設不會 Fallthrough,匹配到就會自動退出,這避免了許多 Bug。
    • 如果你確實需要 Fallthrough 行為,必須明確加上 fallthrough 關鍵字。
  2. 必須完整 (Exhaustive):Switch 必須涵蓋所有可能的情況。如果沒有涵蓋所有 case,編譯器會報錯。通常我們使用 default 來處理剩餘情況。

區間匹配 (Interval Matching)

Switch 可以匹配數值區間:

let score = 85

switch score {
case 0..<60:
    print("不及格")
case 60..<80:
    print("及格")
case 80...100:
    print("優秀")
default:
    print("分數不合理")
}

元組匹配 (Tuple Matching)

你可以同時測試多個值:

let point = (1, 1)

switch point {
case (0, 0):
    print("在原點")
case (_, 0): // 使用 _ 忽略不需要匹配的部分
    print("在 X 軸上")
case (0, _):
    print("在 Y 軸上")
case (-2...2, -2...2):
    print("在 2x2 的盒子內")
default:
    print("在盒子外")
}

值綁定 (Value Binding)

Switch 可以在匹配時將值綁定到臨時變數,供 case 內使用:

let anotherPoint = (2, 0)

switch anotherPoint {
case (let x, 0):
    print("在 X 軸上,X 值為 \(x)")
case (0, let y):
    print("在 Y 軸上,Y 值為 \(y)")
case let (x, y):
    print("在某個地方 (\(x), \(y))")
}

Where 子句

你可以使用 where 子句來增加額外的篩選條件:

let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
    print("在 x == y 的線上")
case let (x, y) where x == -y:
    print("在 x == -y 的線上")
default:
    print("其他位置")
}

如你所見,Swift 的 Switch 非常靈活,它是處理複雜條件邏輯的利器。