Understanding Comparision Operator
Introduction to Comparision Operator in Swift
Comparison operators are fundamental tools in Swift, enabling developers to compare values and expressions efficiently. These operators return Boolean values (true or false) and are widely used in loops and conditional statements to control program flow.
List of Swift Comparison Operators
Name | Example | Output |
---|---|---|
Equal to (==) | 56 == 56 | true |
Not Equal to (!=) | 56 != 78 | true |
Greater than (>) | 56 > 32 | true |
Less than (<) | 44 < 67 | true |
Greater than or Equal to (>=) | 77 >= 33 | true |
Less than or Equal to (<=) | 21 <= 56 | true |
Using the Equal to (==) Operator
The == operator checks whether two values are identical.
Syntax:
value1 == vlaue2
import
Foundation
let password
= "XP123"
if password
== "XP123" {
print("Welcome!! Entered password is correct")
} else {
print("Error!!! Please enter the correct password")
}
Output
Using the Not Equal to (!=) Operator
The != operator verifies if two values are different.
Syntax:
value1 != vlaue2
Example
import
Foundation
let str
= "ali"
if str
!= "Ahmed" {
print("Both strings are not equal")
} else {
print("Both strings are equal")
}
Output
Using the Greater than (>) Operator
The > operator checks if the left-hand value is greater than the right-hand value.
Syntax:
value1 > vlaue2
Example: Summing Values Greater Than 50
import
Foundation
let arr
= [3, 55,
2, 44,
66]
var sum
= 0
for x
in arr {
if x
> 50 {
sum +=
x
}
}
print("Sum = \(sum)")
Output
Using the Less than (<) Operator
The < operator verifies if the left-hand value is smaller than the right-hand value.
Syntax:
value1 < vlaue2
import
Foundation
let arr
= [1, 55,
2, 90,
12]
var sum
= 0
for x
in arr {
if x
< 55 {
sum +=
x
}
}
print("Sum = \(sum)")
Output
Using the Greater than or Equal to (>=) Operator
The >= operator confirms whether the left-hand value is greater than or equal to the right-hand value.
Syntax
value1 >= vlaue2
Example: Checking Voting Eligibility
import
Foundation
let age
= 18
if age
>= 18 {
print("You are eligible for voting")
} else {
print("You are not eligible for voting")
}
Output
Using the Less than or Equal to (<=) Operator
The <= operator determines if the left-hand value is less than or equal to the right-hand value.
Syntax:
value1 <= vlaue2
Example
import
Foundation
let num
= 18
if num
<= 20 {
print("Given number is less than or equal to 20")
} else {
print("Given number is greater than 20")
}