基本条件 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")
}