Swift: Combining Logical Operators

Combining Logical Operators in Swift:

Swift allows us to chain logical operators like &&, ||, and ! to make longer, more complex compound expressions. Combining logical operators in Swift helps us to solve many problems.

Consider the following if statement, which uses the && and || operators as part of its condition:

var Sunday = true; 
var Holiday = true; 
var Work = false;
if Sunday && Work || Holiday {
  print("Have fun!"); 
} else {
  print("Do your work!"); 
// Prints: Have fun!

When the values of Sunday and Work are combined with the && operator, the result is false. This value is then used to execute the expression false OR Holiday, which returns true. As a result, the entire condition is true, and the first code block is run.

The && operator is more important than the || operator. This rule tells our program to run the &&-containing expression first, then use the result to calculate the rest of the expression.

Rearranging the previous condition like this would result in Sunday && Work still executing first.

Holiday || Sunday && Work

For more information on operator precedence in Swift, see this documentation.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: