An if
statement checks whether a Bool condition is 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
statements accept else if
and else
blocks, which can test alternate conditions and provide a fallback:
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")
}
Basic operators like &&
and ||
can be used for multiple conditions:
let num = 10
let str = "Hi"
if num == 10 && str == "Hi" {
print("num is 10, AND str is \"Hi\"")
}
If num == 10
was false, the second value wouldn't be evaluated. This is known as short-circuit evaluation.
if num == 10 || str == "Hi" {
print("num is 10, or str is \"Hi\")
}
If num == 10
is true, the second value wouldn't be evaluated.
if !str.isEmpty {
print("str is not empty")
}