OneBite.Dev - Coding blog in a bite size

Check If Two Variable Is Not Equal In Swift

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

Swift is a popular coding language used for iOS applications. This article will guide you on how to check if two variables are not equal in Swift.

Code snippet: Checking if two Variables are not Equal in Swift

Let’s create a simple Swift code to check this:

Swift 5.x

let firstVariable = 5
let secondVariable = 10

if firstVariable != secondVariable {
  print("The two variables are not equal.")
} else {
  print("The two variables are equal.")
}

In this instance, the console would print “The two variables are not equal.” because 5 is not equal to 10.

Code Explanation for Checking if two Variables are not Equal in Swift

This Swift code starts by declaring two variables, firstVariable and secondVariable, with values of 5 and 10 respectively.

The next part of the code is a conditional statement, specifically an if statement. This if statement is used to compare the two variables using the “not equal to” operator (!=), which is crucial for this operation.

This operator compares the left operand (firstVariable) with the right operand (secondVariable). If the values of the two variables are not equal, the code block within the if statement gets executed. In this case, it would print “The two variables are not equal.”.

However, if the values of the variables are equal, the code block within the else statement gets executed. This block’s purpose is to handle all cases where the if condition isn’t met. In our case, it would print “The two variables are equal.”.

Remember, Swift uses type-inference, so you should ensure that the compared variables are of the same type. Our example uses integers, but you could compare other data types as well, such as strings or even custom types.

This simple yet critical operation is used frequently in many applications and is fundamental to the development of more complex conditions and statements.

swift