You are currently viewing Swift Relational Operators

Swift Relational Operators

Swift, Apple’s powerful and intuitive programming language, provides a range of relational operators that allow developers to compare values and make decisions in their code. In this article, we will explore Swift’s relational operators, their functionality and provide code examples to solidify your understanding.

What are Relational Operators?

Relational operators are symbols in Swift that enable you to compare values and express relationships between them. Swift provides a set of six standard relational operators.

Equal to Operator (==)

The equal to operator (==) is used to check whether two values are identical. It is crucial to understand that this operator checks for equality in value, not necessarily in memory location.

let appleCount: Int = 5
let orangeCount: Int = 5

if appleCount == orangeCount {
    print("We have an equal number of apples and oranges.")
	
} else {
    print("The number of apples and oranges is different.")
	
}

In this example, the code compares the appleCount and orangeCount variables using the equal to operator. If the counts are equal, the program prints a message indicating the equality; otherwise, it outputs a message stating the difference.

Not Equal to Operator (!=)

Conversely, the not equal to operator (!=) checks if two values are different.

let userName: String = "Edward"
let password: String = "CoderScratchpad"

if userName != password {
    print("Username and password do not match.")
	
} else {
    print("Welcome, \(userName)!")
	
}

This example demonstrates a simple authentication scenario. If the userName and password are not equal, it prints a message indicating a failed authentication attempt; otherwise, it welcomes the user.

Greater Than Operator (>)

The greater than operator (>) checks if the left operand is greater than the right operand.

let myScore: Int = 85
let passingScore: Int = 60

if myScore > passingScore {
    print("Congratulations! You passed the exam.")
	
} else {
    print("Unfortunately, you did not meet the passing score.")
	
}

In this example, the code evaluates whether the myScore is greater than the passingScore and prints an appropriate message based on the result.

Less Than Operator (<)

Conversely, the less than operator (<) determines if the left operand is less than the right operand.

let temperatureInCelsius: Int = 25
let boilingPoint: Int = 100

if temperatureInCelsius < boilingPoint {
    print("The water is not boiling.")
	
} else {
    print("The water is boiling!")
	
}

Here, the program checks if the temperatureInCelsius is less than the boiling point, providing feedback on the water’s boiling status.

Greater Than or Equal To Operator (>=)

The greater than or equal to operator (>=) checks if the left operand is greater than or equal to the right operand.

let age: Int = 28
let legalDrinkingAge: Int = 18

if age >= legalDrinkingAge {
    print("You are eligible to purchase alcoholic beverages.")
	
} else {
    print("Sorry, you must be \(legalDrinkingAge) or older to buy alcohol.")
	
}

In this example, the code determines whether the age is equal to or greater than the legal drinking age, allowing or denying access to purchasing alcoholic beverages.

Less Than or Equal To Operator (<=)

Conversely, the less than or equal to operator (<=) checks if the left operand is less than or equal to the right operand.

let remainingFuel: Int = 15
let minimumFuelRequired: Int = 20

if remainingFuel <= minimumFuelRequired {
    print("Low fuel! Visit the nearest gas station.")
	
} else {
    print("You have enough fuel to continue your journey.")
	
}

Here, the code alerts the user if the remaining fuel is less than or equal to the minimum required amount.

Identical To (===) and Not Identical To Operators (!==)

Swift provides additional operators for reference types, known as the identity operators. The identical-to operator (===) checks if two objects refer to the exact same instance, while the not-identical-to operator (!==) checks if they do not refer to the same instance.

Let’s see these operators in action:

class Person {

    var name: String
    
    init(name: String) {
        self.name = name
    }
    
}

let person1 = Person(name: "Edward")
let person2 = Person(name: "Edward")
let person3 = person1

if person1 === person2 {
    print("person1 and person2 are identical")
	
} else {
    print("person1 and person2 are not identical")
	
}

if person1 !== person3 {
    print("person1 and person3 are not identical")
	
} else {
    print("person1 and person3 are identical")
	
}

In this example, the first if statement prints “person1 and person2 are not identical” because even though their properties are the same, they are distinct instances. The second if statement prints “person1 and person3 are identical” as they both refer to the same instance.

Conclusion

Relational operators are fundamental to programming, allowing developers to make decisions based on the relationships between values. In Swift, the set of operators discussed here provides a robust foundation for comparing and evaluating different types of data. Mastering these operators will enhance your ability to create clear and concise code for a wide range of scenarios.

Sources:

Leave a Reply