Menu
Coddy logo textTech

Comparison Operators

Part of the Fundamentals section of Coddy's Swift journey — lesson 20 of 86.

Comparison operators let you compare two values and determine their relationship. Unlike arithmetic operators that produce numbers, comparison operators always return a Bool — either true or false.

Swift provides six comparison operators:

let a = 10
let b = 5

print(a == b)  // false (equal to)
print(a != b)  // true  (not equal to)
print(a > b)   // true  (greater than)
print(a < b)   // false (less than)
print(a >= b)  // true  (greater than or equal to)
print(a <= b)  // false (less than or equal to)

These operators work with numbers, strings, and other comparable types. For strings, Swift compares them alphabetically:

print("apple" < "banana")  // true
print("cat" == "cat")      // true

Comparison operators are essential for making decisions in your code. You'll use them constantly when checking conditions, validating input, or determining which action to take based on values.

challenge icon

Challenge

Easy

You are provided with the following variables:

let x = 15
let y = 20
let z = 15

Use comparison operators to evaluate and print the result of each comparison below, in this exact order:

  1. Is x equal to z?
  2. Is x not equal to y?
  3. Is y greater than x?
  4. Is x less than z?
  5. Is y greater than or equal to 20?
  6. Is x less than or equal to 10?

Print each result on a separate line.

Cheat sheet

Comparison operators compare two values and return a Bool (true or false).

Swift provides six comparison operators:

let a = 10
let b = 5

print(a == b)  // false (equal to)
print(a != b)  // true  (not equal to)
print(a > b)   // true  (greater than)
print(a < b)   // false (less than)
print(a >= b)  // true  (greater than or equal to)
print(a <= b)  // false (less than or equal to)

Comparison operators also work with strings, comparing them alphabetically:

print("apple" < "banana")  // true
print("cat" == "cat")      // true

Try it yourself

let x = 15
let y = 20
let z = 15

// TODO: Write your code below
// Use comparison operators to evaluate each comparison and print the results
// 1. Is x equal to z?
// 2. Is x not equal to y?
// 3. Is y greater than x?
// 4. Is x less than z?
// 5. Is y greater than or equal to 20?
// 6. Is x less than or equal to 10?
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals