Skip to main content

guard

當然可以! 🚀

在 Swift 裡,guard 是一個用來「提前處理例外情況」的語法,常用來避免巢狀 if,讓程式碼更清楚。

基本語法

guard 條件 else {
// 條件不成立時要做的事
// 一定要離開當前作用域,例如 return、break、continue、throw
}

意思是: 👉 如果 條件成立 → 繼續往下執行。 👉 如果 條件不成立 → 執行 else 裡的程式,然後「跳出」當前區塊。

範例 1:檢查輸入是否有效

func greet(_ name: String?) {
guard let name = name else {
print("名字不能是 nil")
return
}
print("Hello, \(name)!")
}

greet(nil) // 👉 名字不能是 nil
greet("Thomas") // 👉 Hello, Thomas!

這裡用 guard let 來安全解包 (Optional Binding),如果 namenil,就直接 return

範例 2:避免巢狀 if

沒有用 guard

func process(age: Int?) {
if let age = age {
if age >= 18 {
print("成年人")
} else {
print("未成年")
}
} else {
print("沒有年齡資料")
}
}

guard

func process(age: Int?) {
guard let age = age else {
print("沒有年齡資料")
return
}
print(age >= 18 ? "成年人" : "未成年")
}

👉 可讀性更高,不需要一層層 if

範例 3:迴圈裡用 guard

let numbers = [1, -2, 3, -4, 5]

for num in numbers {
guard num > 0 else {
continue // 跳過不符合條件的數字
}
print("正數:\(num)")
}
// 👉 印出 1, 3, 5

總結

  • guard 常用來 提前處理錯誤或例外
  • else 區塊 必須 讓控制流程離開當前作用域(例如 returnthrowcontinuebreak)。
  • 讓程式碼更「平坦」,避免過度縮排。