Comparison operators - Swift Tutorial

Ozan Emre Duran
AppleCode Chronicles
2 min readJun 6, 2023

In Swift, comparison operators play a vital role in determining the relationship between different values. These operators allow you to compare variables, constants, or expressions and make decisions based on their outcome. Whether you’re working with numbers, strings, or other data types, understanding Swift’s comparison operators is crucial for controlling the flow of your code.

Equal to (==): This operator checks whether two values are equal.

let a = 5 
let b = 10
if a == b {
// Code if a is equal to b
} else {
// Code if a is not equal to b
}

Not equal to (!=): This operator checks whether two values are not equal.

let a = 5 
let b = 10
if a != b {
// Code if a is not equal to b
} else {
// Code if a is equal to b
}

Greater than (>): This operator checks whether the left operand is greater than the right operand.

let a = 5 
let b = 10
if a > b {
// Code if a is greater than b
} else {
// Code if a is less than or equal to b
}

Less than (<): This operator checks whether the left operand is less than the right operand.

let a = 5 
let b = 10
if a < b {
// Code if a is less than b
} else {
// Code if a is greater than or equal to b
}

Greater than or equal to (>=): This operator checks whether the left operand is greater than or equal to the right operand.

let a = 5 
let b = 10
if a >= b {
// Code if a is greater than or equal to b
} else {
// Code if a is less than b
}

Less than or equal to (<=): This operator checks whether the left operand is less than or equal to the right operand.

let a = 5 
let b = 10
if a <= b {
// Code if a is less than or equal to b
} else {
// Code if a is greater than b
}

These operators can be used with various data types in Swift, such as integers, floating-point numbers, strings, and more. They are commonly used in conditional statements (if-else) to control the flow of execution based on the result of the comparison.

If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!

Click here for Notion Swift Tutorial Template :)

--

--

Ozan Emre Duran
AppleCode Chronicles

I'm a passionate programmer who loves exploring and using Apple products. Swift is my language of choice.