OneBite.Dev - Coding blog in a bite size

Check If Two Variable Not Equal In Swift

Code snippet for how to Check If Two Variable Not Equal In Swift with sample and detail explanation

In this article, we’ll explore how to check if two variables are not equal in Swift, a critical aspect of programming logic that supports decision-making processes in your code. By understanding this comparison, you can better manage and design your program’s flow.

Code Snippet: Checking If Two Variables Aren’t Equal in Swift

Here’s a quick example to illustrate:

let variable1 = 5
let variable2 = 10

if variable1 != variable2 {
   print("The variables are not equal")
} else {
   print("The variables are equal")
}

This snippet executes a simple task: it compares two variables (variable1 and variable2), and prints a different statement depending on their equality.

Code Explanation: Checking If Two Variables Aren’t Equal in Swift

Let’s break down the code snippet step by step for a better understanding:

  1. First, we’re defining two variables: variable1, which is equal to 5, and variable2, which is equal to 10.
let variable1 = 5
let variable2 = 10
  1. Next, we’re using an if statement to state our condition: if variable1 != variable2. Here, != is the does not equal operator in Swift. So, this line checks if variable1 does not equal variable2.
if variable1 != variable2 {
  1. If variable1 is not equal to variable2, the code within this if block will be executed. In this case, we’re just printing a statement: “The variables are not equal”.
print("The variables are not equal")
  1. But what if variable1 equals variable2? That’s what the else statement covers. If the condition in the if statement isn’t met, the logic jumps to the else block, in which we’re also printing a statement: “The variables are equal”.
} else {
   print("The variables are equal")
}

Hence, this Swift code allows us to compare two variables and act differently based on whether they’re equal or not. It’s a fundamental practice in coding that’s widely applicable in many programming scenarios.

swift