0
0
Swiftprogramming

Comparison operators in Swift

Choose your learning style9 modes available
Introduction

Comparison operators help us check if things are equal or which one is bigger or smaller. They let the program make decisions.

Checking if a password matches the saved one.
Deciding if a player's score is higher than the high score.
Finding out if a number is less than 10 to give a special message.
Comparing two dates to see which comes first.
Checking if two strings are the same to avoid duplicates.
Syntax
Swift
a == b   // equal to
a != b   // not equal to
a > b    // greater than
a < b    // less than
a >= b   // greater than or equal to
a <= b   // less than or equal to

Use these operators inside conditions like if or while to control the flow.

They return a Bool value: true or false.

Examples
Checks if x equals y. Here, 5 is not equal to 10, so it prints false.
Swift
let x = 5
let y = 10
print(x == y)  // false
Checks if a is greater than b. Since 7 is greater than 3, it prints true.
Swift
let a = 7
let b = 3
print(a > b)   // true
Checks if two strings are not equal. They are equal, so it prints false.
Swift
let name1 = "Anna"
let name2 = "Anna"
print(name1 != name2)  // false
Sample Program

This program checks the temperature and prints a message based on comparison operators.

Swift
let temperature = 30
if temperature > 25 {
    print("It's hot outside!")
} else if temperature == 25 {
    print("It's warm today.")
} else {
    print("It's cool outside.")
}
OutputSuccess
Important Notes

Remember that == checks for equality, not assignment.

Use parentheses () to group comparisons if needed for clarity.

Summary

Comparison operators compare two values and return true or false.

They are used to make decisions in code, like in if statements.

Common operators include ==, !=, >, <, >=, and <=.