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 // falseA few details:
- One
=assigns; two==compare.done = 5changesdone,done == 5asks about it. - Both sides must be the same type. Comparing an
Intwith aStringdoes not compile. - Strings compare by their characters, in character order, so
"Read" == "read"isfalse, and"Apple" < "Banana"istrue. - No chaining.
1 < streak < 10is 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.
The line
let label = minutes >= 20 ? "Done" : "\(20 - minutes) min left"withminutesequal to 14.
Drills
Answer fast — trust the rule.
What type is the value of streak > 7?
What is "Walk" == "walk"?
With done = 5 and goal = 5, what is done >= goal ? "Done" : "Not yet"?
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.
