Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Operators  ›  Lesson

Comparison Operators

Comparison 12 minComparison operators such as ==, != and < always produce a Bool, which can be stored, used as a condition or fed into the ternary operator.

Comparison Operators

"Has today's goal been met?" "Is this the longest streak ever?" Most of Sprout's decisions start with a comparison. Every one of them produces the same kind of answer, and knowing that makes the next lessons easy.

The rule

A comparison asks a question and always answers with a Bool.

The six comparison operators:

Operator Question done = 3, goal = 5
== equal? done == goal is false
!= not equal? done != goal is true
< less than? done < goal is true
> greater than? done > goal is false
<= less or equal? done <= 3 is true
>= greater or equal? done >= goal is false

Because the answer is a Bool, you can store it, print it, or use it as a condition:

let goalMet = done >= goal       // false

A few details:

  • One = assigns; two == compare. done = 5 changes done, done == 5 asks about it.
  • Both sides must be the same type. Comparing an Int with a String does not compile.
  • Strings compare by their characters, in character order, so "Read" == "read" is false, and "Apple" < "Banana" is true.
  • No chaining. 1 < streak < 10 is not allowed. Split it into two comparisons joined by &&, the next lesson's topic.

The ternary operator turns a comparison into a choice between two values:

let label = done >= goal ? "Goal met" : "Keep going"

Read it as "question, then value if yes, colon, value if no".

The shortcut

Say the comparison aloud as a yes-or-no question, then answer it: "is three greater than or equal to five?" No, so false. For a ternary, answer the question first, then take the value on the matching side of the colon.

Sprout's progress labelStep 1 of 4
  1. The line

    let label = minutes >= 20 ? "Done" : "\(20 - minutes) min left" with minutes equal to 14.

Drills

Answer fast — trust the rule.

quick drill

What type is the value of streak > 7?

quick drill

What is "Walk" == "walk"?

quick drill

With done = 5 and goal = 5, what is done >= goal ? "Done" : "Not yet"?

quick drill

Why does if 1 < streak < 10 { } fail to compile?

Remember

  • A comparison asks a question and always answers with a Bool.
  • Say it aloud as a yes-or-no question; for ? :, take the matching side.
  • = assigns, == compares, and comparisons do not chain.

Practice — level up

0/1 solved

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

ExplainExplain the progress label

Explain step by step what let label = minutes >= goal ? "Done" : "\(goal - minutes) min left" produces when minutes is 25 and goal is 30, and again when minutes is 30.