基本條件 if 語句

一個 if 語句檢查是否一個布林條件是 true

let num = 10

if num == 10 {
    // Code inside this block only executes if the condition was true.
    print("num is 10")
}

let condition = num == 10   // condition's type is Bool
if condition {
    print("num is 10")
}

if 語句接受 else ifelse 塊,它可以測試備用條件並提供後備:

let num = 10
if num < 10 {  // Execute the following code if the first condition is true.
    print("num is less than 10")
} else if num == 10 {  // Or, if not, check the next condition...
    print("num is 10")
} else {  // If all else fails...
    print("all other conditions were false, so num is greater than 10")
}

&&||等基本操作符可用於多種條件:

邏輯 AND 運算子

let num = 10
let str = "Hi"
if num == 10 && str == "Hi" {
    print("num is 10, AND str is \"Hi\"")
}

如果 num == 10 為 false,則不會評估第二個值。這被稱為短路評估。

邏輯 OR 運算子

if num == 10 || str == "Hi" {
    print("num is 10, or str is \"Hi\")
}

如果 num == 10 為 true,則不會評估第二個值。

邏輯 NOT 運算子

if !str.isEmpty {
    print("str is not empty")
}