When writing if statements, we usually compare two values using one or more comparison operators:
| Operator | Name | Examples |
|---|---|---|
| == | Equal | x == 5, x == y |
| != | Not equal | x != 3, x != y |
| > | Greater than | x > 5, x > y |
| < | Less than | x < 8, x < y |
| >= | Greater than or equal to | x >= 4, x >= y |
| <= | Less than or equal to | x <= 3, x <= y |
For example:
10 == 10 // Evaluates to true
3 < 2 // Evaluates to false
15 >= 15 // Evaluates to true
17 != 12 // Evaluates to true
We usually use these operators with variables:
var a = 10
var b = 15
if a == b {
print("a is equal to b")
}
if a < b {
print("a is less than b")
}
The first condition is not satisfied since 10 == 15 evaluates to false.
The second condition is satisfied since 10 < 15 evaluates to true.
The code above prints "a is less than b".
Assignment
Follow the Coding Tutorial and let's play with comparison operators.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.