Start learning free

LESSON 70 OF 415 · CONDITIONAL STATEMENTS

Comparison Operators in Swift

Lesson Read the full explanation

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.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    Comparison Operators in Swift, explained

    What comparison operators do

    A comparison operator looks at two values and produces a Bool: true or false. That result is what an if statement needs as its condition, so comparisons are how a Swift program decides what to do.

    OperatorMeaningExample
    ==equal tox == 5
    !=not equal tox != 3
    >greater thanx > 5
    <less thanx < 8
    >=greater than or equal tox >= 4
    <=less than or equal tox <= 3

    Each one works on literals and on variables alike. With a set to 10 and b set to 15:

    let a = 10
    let b = 15
    print(a == b, a != b, a < b, a > b, a >= 10, a <= 9)
    
    false true true false true false
    

    Using comparisons in an if statement

    The result of a comparison goes straight into an if:

    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, 10 == 15, is false, so its block is skipped. The second, 10 < 15, is true, so the program prints a is less than b. Swift needs no parentheses around the condition, but the braces around each body are required.

    Details that matter in Swift

    • == compares, = assigns. Writing if x = 5 { is a compile error, so the mix-up can't slip through silently.
    • Both sides must have the same type. Swift does not convert between Int and Double for you. With let a = 3 and let d = 3.5, the test a < d fails with binary operator '<' cannot be applied to operands of type 'Int' and 'Double'. Convert one side explicitly: Double(a) < d. Comparing a number with a string, such as grade == "8", is an error for the same reason.
    • Strings compare too. "apple" == "apple" is true, and "apple" < "banana" is true because the comparison is alphabetical. It is case-sensitive, though: "Zebra" < "apple" is also true, because uppercase letters sort before lowercase ones.
    • No chained comparisons. 1 < x < 10 does not compile. Swift reports that the adjacent operators are in a non-associative precedence group. Join two comparisons with && instead: 1 < x && x < 10.
    • Decimals are inexact. 0.1 + 0.2 == 0.3 is false for Double values, since they store binary approximations. Avoid == on computed decimals.
    • Tuples compare element by element. (3, "a") < (3, "b") is true: the first elements are equal, so the second decides.
    • === is a different operator. It checks whether two class instances are the very same object, and has nothing to do with the numeric comparisons here.

    The exercise

    The starting code has one line, let grade = 8. The task is to report whether the test was failed or passed, where a grade below 5 means failed and 5 or more means passed.

    1. Write the if. The condition is grade < 5. The < operator is true only when the left side is strictly smaller, so a grade of exactly 5 is not a failure.
    2. Print the failure. Inside the braces, print("Failed the test") writes the message on its own line.
    3. Add the else. It needs no condition, because every grade that isn't below 5 is a pass. It prints "Passed the test".
    let grade = 8
    
    if grade < 5 {
        print("Failed the test")
    } else {
        print("Passed the test")
    }
    

    With grade equal to 8 it prints Passed the test. Grades 4 and below print Failed the test, and 5 prints Passed the test.

    Common mistakes

    • Off by one at the boundary. grade <= 5 would fail a grade of 5. Decide whether the boundary value belongs to the pass or the failure, then pick < or <= accordingly.
    • Swapping the sides. 5 < grade is the same as grade > 5, which is not what the task asks.
    • Adding a second condition to else. The else already covers the opposite case.

    Key takeaways

    • The six operators are ==, !=, >, <, >= and <=, and each produces a Bool.
    • Both operands must share a type, so convert with Double(...) when mixing Int and Double.
    • Combine two comparisons with && rather than chaining them.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free