The logical, &&
, operator evaluates two operands and returns a Boolean result. It returns true
only when both operands are true
and returns false
when at least one operand is false
.
&&
is denoted by two ampersand symbols and translates to AND.
The following truth table demonstrates all of the possible outcomes of an expression using &&
.
Logical Expression | Result |
---|---|
true && true | true |
true && false | false |
false && true | false |
false && false | false |
Let’s see the &&
operator in action. Assume we’re writing a program for an application that dims a screen by 25% in the evening time. We can set up the following if
/else
statement for this case:
var time = 8 // PM var phoneInUse = true var brightness: Double if time >= 8 && phoneInUse { brightness = 0.75 } else { brightness = 1 } print(brightness) // Prints: 0.75
Notice how the brightness will be set to 75% only when time >= 8
and phoneInUse
are both true
. Changing the value of time
to be less than 8 or setting phoneInUse
to false
, would result in the brightness remaining the same.
Instructions
In NewYear.swift, we’ve declared the variables, midnight
and date
to be used within our New Year program.
Below the variables, create an if
statement that:
- Checks if it is
midnight
AND thedate
is"January 1, 2020"
. - Prints the message,
"It's the start of a new decade!"
.
Continue practicing in the editor by testing your code with different values for midnight
or date
. Make sure your code is working as expected before moving on.