Swift: Comparison Operators

Comparison Operators in Swift:

Our conditions have so far consisted of a single variable with a true or false value. We can extend this by using comparison operators in Swift to create conditions that use multiple values to produce a Boolean result.

We’ll learn about comparison operators in Swift in this exercise. The relationship between two operands is determined by comparison operators, which return a Boolean value.

The comparison operators supported by Swift are:

  • == Equal to
  • != Not Equal to
  • < Less than
  • > Greater than
  • <= Less than or equal to
  • >= Greater than or equal to

Although == and != can also be used to compare String values, comparison operators are most commonly used to compare numerical values such as Integers and Doubles.

7 < 8        // true 
0.8 > 0.2    // true
5.5 <= 5.0   // false
13 >= 17     // false
"Y" == "Y"   // true 
"X" != "x"   // true

Because Swift is a case-sensitive language, a capital "X" is not the same as a lowercase "x".

We can construct the following conditional using our knowledge of if/else statements and comparison operators to check for a student’s exam grade:

let marks = 89;
if marks > 50 {
  print("Exam Passed!"); 
} else {
  print("Exam Failed.");

The first code block is executed and prints, Exam Passed!, because the student’s marks is greater than 50.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: