Start learning free

LESSON 74 OF 349 · CONDITIONAL STATEMENTS

Logical Operators: And (&&) in Swift

Lesson

Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if both conditions to the left and right of it are true. For example:

10 == 10 && 7 < 10 // Evaluates to true

We have two conditions separated by && operator:

  • 10 == 10, which evaluates to true
  • 7 < 10, which evaluates to true
As both conditions evaluate to true, the entire line will evaluate to true

An example inside an if statement:

let x = 10
if x != 7 && 12 < x { // Evaluates to false
    print("This is true!")
}

Inside the if, we have two conditions separated by && operator:

  • x != 7, equivalent to 10 != 7, which evaluates to true
  • 12 < x, equivalent to 12 < 10, which evaluates to false
As one of the conditions evaluates to false, the entire statement will evaluate to false, and so the program prints nothing.

Assignment
Follow the Coding Tutorial and play with the and operator.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    And Operator in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free