Learn

Swift allows us to combine or chain logical operators, &&, ||, and ! in order to create longer, more complex compound expressions.

Take a look at the following if statement that utilizes the && and || operator in its condition:

let weekday = true let dayOff = false let weekend = false if weekday && dayOff || weekend { print("Do something fun!") } else { print("Get some work done") } // Prints: Get some work done

Combining the value of weekday and dayOff with the && operator will result in false. This resulting value is then used to execute the expression false OR weekend which is false. Thus, the entire condition results in false and the second code block is executed.

Note that when chaining Swift’s logical operators, we must keep in mind the order in which execution happens.

The && operator has higher precedence over the || operator.

This rule instructs our program to execute the expression containing the && first, and then use that result to calculate the rest of the expression.

For instance, rearranging the previous condition to…

weekend || weekday && dayOff

would result in weekday && dayOff still executing first.

Reference this documentation for more information about operator precedence in Swift.

Instructions

1.

In order to access an iPhone, Apple requires that you enter the correct password or get access through TouchID. 📱

In Security.swift, we’ve provided three variables that represent these cases. We’ll use them and logical operators to build a program that grants or denies a user access.

First, create an if statement with the following logic:

If a user enters the correctPassword AND had lessThanThreeTries OR has accessThroughTouchID, then set unlock to true.

2.

Add an else statement and within its body, reassign unlock to false.

3.

Following the if/else statement, print the value of unlock.

4.

Continue practicing in the editor by testing your code with different Boolean values for correctPassword, lessThanThreeTries and accessThroughTouchID. In which cases do you think the phone would NOT get unlocked?

Make sure your code is working as expected before moving on.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?