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!
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.
== (equal to)!= (not equal to)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
}< (less than)> (greater than)<= (less than or equal to)>= (greater than or equal to)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
}Swift also provides compound comparison operators, which can compare values based on multiple conditions.
&&&& checks if both conditions are true.
let i = 5
let j = 10
if i < 10 && j > 10 {
print("Both conditions are true") // Output: Both conditions are false
}|||| checks if at least one condition is true.
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 can also be used with ranges to check if a value falls within a specific range.
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
}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! 🚀💻