Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Operators  ›  Lesson

Logical Operators

Logical 12 minThe logical operators not, and and or combine Bool values, evaluate left to right, stop as soon as the result is decided, and group and before or.

Logical Operators

Sprout should show a celebration only when today's goal is met and the streak is a new record, and a nudge when the goal is not met or the user skipped yesterday. Real conditions are built from smaller ones. Logical operators are the glue.

The rule

&& needs both, || needs either, ! flips; stop once decided.

The three logical operators take Bools and give a Bool:

  • NOT, !a: flips the value. !true is false.
  • AND, a && b: true only if both are true.
  • OR, a || b: true if at least one is true.
let goalMet = true
let isRecord = false
let skippedYesterday = true

goalMet && isRecord             // false: one side is false
!goalMet || skippedYesterday    // true: the right side is true
!isRecord                       // true

Short-circuiting. Swift stops as soon as the answer is known. In a && b, if a is false the whole thing is false, so b is never evaluated. In a || b, if a is true, b is skipped. This is useful: put a safe check first, then the one that depends on it.

!habits.isEmpty && habits[0] == "Read"   // never reads habits[0] from an empty list

Grouping. && is applied before ||, just as multiplication comes before addition. Do not rely on that when reading gets hard: add brackets to show your intent.

(goalMet && isRecord) || isBirthday

The shortcut

Read && as "both", || as "either", ! as "not". Then evaluate left to right and stop the moment the answer is fixed: a false before &&, or a true before ||, decides that part without looking further.

Should Sprout celebrate?Step 1 of 4
  1. The rule

    Celebrate if goalMet && (isRecord || isFirstDay). Here goalMet is true, isRecord false, isFirstDay true.

Drills

Answer fast — trust the rule.

quick drill

What is true && false?

quick drill

Which Swift expression means "goal NOT met"?

quick drill

In isPaused && expensiveCheck(), isPaused is false. What happens to expensiveCheck()?

quick drill

With a = false, b = true, c = true, what is a && b || c?

Remember

  • && needs both, || needs either, ! flips; stop once decided.
  • Put the safe check first so short-circuiting protects the next one.
  • && groups before ||, but brackets make it clear to readers.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainDesign the celebration rule

Write a Swift condition for 'show a nudge if the goal is not met and it is after 8 pm, or if the user skipped yesterday', using goalMet, isAfter8pm and skippedYesterday. Explain how it is grouped and what short-circuiting skips.