Boolean logic

Each of the examples above tests just one condition. When George Boole invented the Boolean, he had much more planned for it than these humble beginnings. He

invented Boolean logic, which lets you combine multiple conditions to form a result.

One way to combine conditions is by using AND. When you AND together two Booleans, the result is another Boolean. If both input Booleans are true, then the result is true. Otherwise, the result is false.

In Swift, the operator for Boolean AND is &&, used like so:

let and = true && true

In this case, and will be true. If either of the values on the right was false, then and

would be false.

Another way to combine conditions is by using OR. When you OR together two Booleans, the result is true if either of the input Booleans is true. Only if both input Booleans are false will the result be false.

In Swift, the operator for Boolean OR is ||, used like so:

let or = true || false

In this case, or will be true. If both values on the right were false, then or would be false. If both were true, then or would still be true.

In Swift, Boolean logic is usually applied to multiple conditions. Maybe you want to determine if two conditions are true; in that case, you’d use AND. If you only care about whether one of two conditions is true, then you’d use OR.

For example, consider the following code:

let andTrue = 1 < 2 && 4 > 3

let andFalse = 1 < 2 && 3 > 4

let orTrue = 1 < 2 || 3 > 4

let orFalse = 1 == 2 || 3 == 4

Each of these tests two separate conditions, combining them with either AND or OR.

It’s also possible to use Boolean logic to combine more than two comparisons. For example, you can form a complex comparison like so:

let andOr = (1 < 2 && 3 > 4) || 1 < 4

The parentheses disambiguates the expression. First Swift evaluates the sub- expression inside the parentheses, and then it evaluates the full expression, following these steps:

1. (1 < 2 && 3 > 4) || 1 < 4

  1. (true && false) || true
  2. false || true
  3. true

results matching ""

    No results matching ""