Logical operators (!, &&, ||)
Logical operators return a Bool
to indicate whether or not a given statement is true. They are used heavily in if statements.
Logical NOT !
let name = "Tomoko"
print(name.isEmpty) // false
print(!name.isEmpty) // true
if !name.isEmpty {
print("name is not empty") // name is not empty
}
Logical AND &&
let loggedIn = true
let accountConfirmed = true
if loggedIn && accountConfirmed {
print("The user is logged in and their account is confirmed.")
} else {
print("Either not logged in, account not confirmed, or both.")
}
// The user is logged in, and their account is confirmed.
Logical OR ||
let loggedIn = true
let accountConfirmed = false
if loggedIn || accountConfirmed {
print("Either logged in, account confirmed, or both.")
} else {
print("Not logged in and account not confirmed.")
}
// Either logged in, account confirmed, or both.
Combining logical operators
Multiple logical operators can be combined to create longer expressions. Although operators &&
and ||
are left-associative, it is usually beneficial to include parentheses for readability.
let loggedIn = true
let accountConfirmed = true
let browsingAsGuest = false
if (loggedIn && accountConfirmed) || browsingAsGuest {
print("The user is logged in with a confirmed account, or they are browsing as guest.")
}
// The user is logged in with a confirmed account, or they are browsing as guest.