OneBite.Dev - Coding blog in a bite size

Check If Two Arrays Are Equal In Swift

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

In app development, there are instances where we need to check if two arrays in Swift are identical or not. This article will present a simple method to assess if two arrays are equal or not in Swift.

Code snippet to check if two arrays are equal in Swift

Below is a concise code snippet that you can use to evaluate if two arrays are equal.

let array1 = [1, 2, 3, 4, 5]
let array2 = [1, 2, 3, 4, 5]

if array1 == array2 {
    print("The two arrays are equal.")
} else {
    print("The two arrays are not equal.")
}

Code Explanation for Checking If Two Arrays Are Equal

Let’s break down the code step by step.

  1. Defining the Arrays: The first two lines of the code define two arrays array1 and array2 that comprise of numbers ranging from 1 to 5.
let array1 = [1, 2, 3, 4, 5]
let array2 = [1, 2, 3, 4, 5]
  1. Checking Equality: The ‘if’ statement is used to compare these two arrays. In Swift, you can directly compare two arrays with ’==’ operator, which checks whether the arrays have the same elements in the same order.
if array1 == array2
  1. Printing the Result: Depending on whether the arrays are identical, one of the two messages will be printed by the ‘print’ function. If the elements and their arrangement in both arrays are identical, “The two arrays are equal.” is printed.
print("The two arrays are equal.")

If they are not identical, “The two arrays are not equal.” is printed.

print("The two arrays are not equal.")

This handy approach can help you quickly compare arrays in Swift. This can be useful in numerous situations when developing apps, such as game logic, checking user selections, data validation, and many more.

swift