Swift: Logical AND Operator

Logical AND Operator in Swift:

Because the logical AND operator in Swift compares two operands and returns a Boolean value. So, it only returns true if both operands are true, and false if at least one operand is false.

&& stands for AND and is represented by two ampersand symbols.

The truth table below shows all of the possible outcomes of an expression with the && operator.

Logical ExpressionResult
true && truetrue
true && falsefalse
false && truefalse
false && falsefalse

Let’s look at how the && operator works. Assume we’re writing a program for an evening-time application that dims a screen by 35%. For this case, we can use the following if/else statement:

var clock = 7 // PM 
let usePhone = true 
var phoneBrightness: Float
 
if clock >= 7 && usePhone {
  phoneBrightness = 0.65 
} else {
  phoneBrightness = 1 
}
 
print(phoneBrightness) // Prints: 0.65

Notice how only when clock >= 7 and usePhone are both true will the brightness be set to 65%. The brightness would remain the same if the value of clock was less than 7 or if usePhone was set to false.

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: