Swift 條件判斷 if else 與 guard

決定程式該走哪條路,是程式邏輯的核心。Swift 提供了 ifguard 兩種方式來進行條件判斷。

If 語句

if 是最基本的條件判斷語句,如果條件為 true,就執行大括號內的程式碼。

var temperatureInCelsius = 30

if temperatureInCelsius >= 30 {
    print("天氣很熱")
} else if temperatureInCelsius >= 20 {
    print("天氣舒適")
} else {
    print("天氣很冷")
}
在 Swift 中,條件表達式 (如 temperatureInCelsius >= 30) 不需要用小括號 () 包起來,但執行區塊的大括號 {}必須的

Guard 語句

guard 是 Swift 特有且非常強大的特性,它專門用於「早期退出」(Early Exit)。

guard 的邏輯是:「確保 (Guard) 這個條件成立,否則 (else) 離開這裡。」

func greet(person: [String: String]) {
    // 確保 person 字典裡有 "name" 這個鍵
    // 如果沒有,就進入 else 區塊並 return
    guard let name = person["name"] else {
        print("沒有名字無法打招呼")
        return
    }
    
    // 如果通過了 guard,name 變數在這裡依然可以使用!
    print("Hello, \(name)!")
    
    // 確保這裡有 "location"
    guard let location = person["location"] else {
        print("Hello \(name), 我不知道你在哪")
        return
    }
    
    print("希望 \(location) 天氣不錯")
}

greet(person: ["name": "Mike", "location": "Taipei"])

為什麼要用 Guard?

你可能會問,用 if 不也是可以嗎?

// 使用 if 的版本 (巢狀地獄)
func greetWithIf(person: [String: String]) {
    if let name = person["name"] {
        if let location = person["location"] {
             print("希望 \(location) 天氣不錯")
        } else {
             print("Hello \(name), 我不知道你在哪")
        }
    } else {
        print("沒有名字無法打招呼")
    }
}

使用 guard 的好處:

  1. 減少巢狀 (Pyramid of Doom):讓主邏輯保持在最外層,程式碼更平坦易讀。
  2. 明確的意圖:一看就知道這裡是「如果不符合就退出」。
  3. 變數作用域guard let 綁定的變數,在 guard 語句之後依然有效,這點與 if let 只有在 {} 內有效不同。
當你需要驗證輸入參數,或者檢查前置條件是否滿足時,優先使用 guard