Swift 5.6: Combining Logical Operators
Let’s define some booleans first:
let enteredDoorCode = true
let passedRetinaScan = false
let hasDoorKey = false
let knowsOverridePassword = true
You can combine multiple logical operators to create longer compound expressions:
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
print(“Welcome!”)
} else {
print(“ACCESS DENIED”)
}
What do you think it would print? Keep you answer in mind
Explicit Parentheses — for Clean Code
It’s sometimes useful to include parentheses when they’re not strictly needed, to make the intention of a complex expression easier to read. In the door access example above, it’s useful to add parentheses around the first part of the compound expression to make its intent explicit:
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
print(“Welcome!”)
} else {
print(“ACCESS DENIED”)
}
What do you think now that it would print?
Note
The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.
And … it prints “Welcome!”
Excerpts From
The Swift Programming Language (Swift 5.6)
Apple Inc.
https://books.apple.com/ro/book/the-swift-programming-language-swift-5-6/id881256329
This material may be protected by copyright.