Swift Comparison Operators 🎯

beginner
10 min

Swift Comparison Operators 🎯

Welcome to the Swift Comparison Operators tutorial! In this lesson, we'll delve into the world of comparison operators in Swift. We'll explore various operators, their usage, and real-world examples to help you grasp the concepts easily. Let's get started!

Understanding Comparison Operators 📝

Comparison operators in Swift are used to compare the values of two or more operands. They help determine relationships between values such as equality, inequality, greater than, lesser than, and more.

Basic Comparison Operators 💡

Equality Operators

  • == (equal to)
  • != (not equal to)
swift
let a = 5 let b = 5 if a == b { print("a is equal to b") // Output: a is equal to b } let c = 10 let d = 5 if c != d { print("c is not equal to d") // Output: c is not equal to d }

Inequality Operators

  • < (less than)
  • > (greater than)
  • <= (less than or equal to)
  • >= (greater than or equal to)
swift
let e = 7 let f = 9 if e < f { print("e is less than f") // Output: e is less than f } let g = 10 let h = 10 if g >= h { print("g is greater than or equal to h") // Output: g is greater than or equal to h }

Compound Comparison Operators 💡

Swift also provides compound comparison operators, which can compare values based on multiple conditions.

Logical AND &&

&& checks if both conditions are true.

swift
let i = 5 let j = 10 if i < 10 && j > 10 { print("Both conditions are true") // Output: Both conditions are false }

Logical OR ||

|| checks if at least one condition is true.

swift
let k = 5 let l = 10 if k < 10 || l > 10 { print("At least one condition is true") // Output: At least one condition is true }

Comparison Operators with Range 💡

Comparison operators can also be used with ranges to check if a value falls within a specific range.

swift
let m = 7 if m >= 1...10 { print("m is within the range 1 to 10") // Output: m is within the range 1 to 10 }

Quiz 💡

Quick Quiz
Question 1 of 1

Which operator is used to check if a variable `a` is greater than or equal to `b` in Swift?

That concludes our Swift Comparison Operators tutorial. We hope you enjoyed learning and mastered the essential comparison operators in Swift. Stay tuned for more exciting lessons! 🚀💻