Swift Comparison Operators
Comparing values and making decisions in Swift
⚖️ What are Comparison Operators?
Comparison operators compare two values and return true or false. Use them to check if values are equal (==), not equal (!=), greater than (>), less than (<), or other relationships between values.
let age = 18
let isAdult = age >= 18 // true
let isChild = age < 13 // false
Swift Comparison Operators
Equal (==)
Checks if two values are equal
let result = 5 == 5 // true
let same = "Hi" == "Hi" // true
Not Equal (!=)
Checks if two values are different
let different = 5 != 3 // true
let notSame = "Hi" != "Bye" // true
Greater Than (>)
Checks if left value is greater
let bigger = 10 > 5 // true
let older = 25 > 18 // true
Less Than (<)
Checks if left value is smaller
let smaller = 3 < 8 // true
let younger = 15 < 21 // true
🔹 Basic Comparison Operations
Compare numbers, strings, and other values:
// Comparing numbers
let a = 10
let b = 5
let isEqual = a == b // false
let isNotEqual = a != b // true
let isGreater = a > b // true
let isLess = a < b // false
let isGreaterOrEqual = a >= b // true
let isLessOrEqual = a <= b // false
// Comparing strings
let name1 = "Alice"
let name2 = "Bob"
let name3 = "Alice"
let sameNames = name1 == name3 // true
let differentNames = name1 != name2 // true
print("10 > 5: \(isGreater)")
print("Alice == Alice: \(sameNames)")
print("Alice != Bob: \(differentNames)")
Output:
10 > 5: true
Alice == Alice: true
Alice != Bob: true
🔹 Greater Than or Equal (>=)
Check if a value is greater than or equal to another:
// Age verification
let userAge = 18
let minimumAge = 18
let canVote = userAge >= minimumAge // true
// Grade checking
let score = 85
let passingGrade = 60
let hasPassed = score >= passingGrade // true
// Price comparison
let budget = 100.0
let itemPrice = 99.99
let canAfford = budget >= itemPrice // true
// String comparison (alphabetical order)
let word1 = "apple"
let word2 = "banana"
let isAlphabeticallyAfter = word1 >= word2 // false
print("Can vote (age \(userAge)): \(canVote)")
print("Passed with score \(score): \(hasPassed)")
print("Can afford $\(itemPrice): \(canAfford)")
Output:
Can vote (age 18): true
Passed with score 85: true
Can afford $99.99: true
🔹 Less Than or Equal (<=)
Check if a value is less than or equal to another:
// Speed limit checking
let currentSpeed = 55
let speedLimit = 60
let isWithinLimit = currentSpeed <= speedLimit // true
// Capacity checking
let currentGuests = 45
let maxCapacity = 50
let hasSpace = currentGuests <= maxCapacity // true
// Temperature checking
let temperature = 32
let freezingPoint = 32
let isFreezing = temperature <= freezingPoint // true
// Discount eligibility
let purchaseAmount = 25.0
let discountThreshold = 50.0
let needsMoreForDiscount = purchaseAmount <= discountThreshold // true
print("Within speed limit: \(isWithinLimit)")
print("Has space for more guests: \(hasSpace)")
print("Temperature is freezing: \(isFreezing)")
Output:
Within speed limit: true
Has space for more guests: true
Temperature is freezing: true
🔹 String Comparisons
Compare strings alphabetically and for equality:
// String equality
let greeting1 = "Hello"
let greeting2 = "Hello"
let greeting3 = "hello"
let exactMatch = greeting1 == greeting2 // true
let caseSensitive = greeting1 == greeting3 // false
// Alphabetical comparison
let firstName = "Alice"
let secondName = "Bob"
let thirdName = "Charlie"
let isAlphabeticallyFirst = firstName < secondName // true
let isAlphabeticallyLast = thirdName > secondName // true
// Case-insensitive comparison
let word1 = "Apple"
let word2 = "apple"
let caseInsensitiveEqual = word1.lowercased() == word2.lowercased() // true
// String length comparison
let shortWord = "Hi"
let longWord = "Hello"
let isShorter = shortWord.count < longWord.count // true
print("Exact match: \(exactMatch)")
print("Alice comes before Bob: \(isAlphabeticallyFirst)")
print("Case-insensitive equal: \(caseInsensitiveEqual)")
print("'Hi' is shorter than 'Hello': \(isShorter)")
Output:
Exact match: true
Alice comes before Bob: true
Case-insensitive equal: true
'Hi' is shorter than 'Hello': true
🔹 Using Comparisons in Conditions
Comparison operators are commonly used in if statements:
// Age-based decisions
let age = 16
if age >= 18 {
print("You can vote!")
} else if age >= 16 {
print("You can drive!")
} else {
print("You're still young!")
}
// Grade evaluation
let testScore = 87
if testScore >= 90 {
print("Grade: A")
} else if testScore >= 80 {
print("Grade: B")
} else if testScore >= 70 {
print("Grade: C")
} else {
print("Grade: F")
}
// Password strength
let password = "mypassword123"
let minLength = 8
if password.count >= minLength {
print("Password meets minimum length requirement")
} else {
print("Password is too short")
}
Output:
You can drive!
Grade: B
Password meets minimum length requirement