When developing apps with Swift, there might be cases where you need to check whether 2 given arrays are equal or not. In Swift, 2 arrays are considered equal when they contain the same elements in the same order. This means that the arrays have the same number of elements, and each element at a given position is equal to the corresponding element in the other array.
This succinct, practical article will walk you through a couple of different ways to perform arrays comparison in Swift. No more delays; let’s kick things off and get to the main points.
Using the == operator
The == operator works by calling the == operator on each pair of elements in the arrays. This means that the elements must conform to the Equatable protocol, which defines how to compare values for equality. Conveniently, most of the standard types in Swift already conform to Equatable, such as Int, String, Bool, etc (If you want to compare arrays of custom types, you need to make sure they conform to Equatable as well).
You can also use the != operator to check if two arrays are not equal.
Example:
let array1 = [1, 2, 3]
let array2 = [1, 2, 3]
let array3 = [3, 2, 1]
// Using the == operator
if(array1 == array2) {
print("array1 and array2 are equal")
} else {
print("array1 and array2 are not equal")
}
// Using the != operator
if(array1 != array3) {
print("array1 and array2 are not equal")
} else {
print("array1 and array2 are equal")
}
Output:
array1 and array2 are equal
array1 and array2 are not equal
Using the elementsEqual(_:) method
The syntax is simple as follows:
if(array1.elementsEqual(array2)){
// so something
}
The elementsEqual(_:) method also works by calling the == operator on each pair of elements in the sequences. However, unlike the == operator, it does not require that the sequences have the same type (for example, you can compare an array and a set using this method).
Example:
let arr1 = ["sling", "academy", "dog"]
let arr2 = ["sling", "academy", "dog"]
let arr3 = ["purple", "cat", "paradise"]
if(arr1.elementsEqual(arr2)){
print("arr1 and arr2 are equal")
} else {
print("arr1 and arr2 are not equal")
}
if(arr1.elementsEqual(arr3)){
print("arr1 and arr3 are equal")
} else {
print("arr1 and arr3 are not equal")
}
Output:
arr1 and arr2 are equal
arr1 and arr3 are not equa
You can also pass a closure to the elementsEqual(_:by:) method to define a custom way of comparing elements. The closure takes two arguments: an element from each sequence and returns a Boolean value indicating whether they are equivalent.
In the following example, we will compare 2 arrays of strings. Our comparison condition here will be relaxed; that is, it is not case-sensitive and does not count leading and trailing whitespace:
import Foundation
let array1 = ["sling", "academy", "swift"]
let array2 = ["Sling", " Academy", "Swift "]
// Using the elementsEqual(_:by:) method with a closure
var result:Bool = array1.elementsEqual(array2) {
$0.trimmingCharacters (
in: .whitespaces).lowercased() == $1.trimmingCharacters (in: .whitespaces).lowercased()
}
print(result)
Output:
true
Using the difference(from:) method
If you want to check if two arrays have different elements, you can use the difference(from:)
method on an array. This method returns a CollectionDifference
value that represents the changes needed to produce one array’s ordered elements from another array’s ordered elements. You can check if the difference is empty or not to determine if there is any difference.
Example:
let array1 = [1, 2, 3]
let array2 = [1, 2, 4]
let array3 = [1, 2, 3]
let difference1 = array1.difference(from: array2)
let difference2 = array1.difference(from: array3)
if(difference1.isEmpty){
print("There is no difference between array1 and array2")
} else {
print("array1 and array2 contain different elements")
}
if(difference2.isEmpty){
print("There is no difference between array1 and array3")
} else {
print("array1 and array3 contain different elements")
}
Output:
array1 and array2 contain different elements
There is no difference between array1 and array3
Comparing nested arrays
To compare two nested arrays in Swift, such as two arrays of dictionaries, you need to make sure that the elements of the arrays are comparable. This means that they conform to the Equatable protocol, which defines how to compare values for equality.
Let’s say you have 2 arrays of dictionaries (the values of a dictionary can be strings or numbers). You can compare them using the == operator or the elementsEqual(_:) method, but you need to make sure that the dictionaries conform to Equatable. One way to do this is to use a typealias and an extension, like this:
// Define an enum that can hold either a string or a number
enum Value {
case string (String)
case number (Double)
}
// Extend the enum to conform to Equatable
extension Value: Equatable {
// Define how to compare two values for equality
static func == (lhs: Value, rhs: Value) -> Bool {
// Switch on the cases of lhs and rhs
switch (lhs, rhs) {
// If both are strings, compare their associated values
case (.string (let s1), .string (let s2)):
return s1 == s2
// If both are numbers, compare their associated values
case (.number (let n1), .number (let n2)):
return n1 == n2
// If they are different cases, return false
default:
return false
}
}
}
// Define a typealias for a dictionary with String keys and Value values
typealias ValueDictionary = [String: Value]
// Define how to compare two dictionaries for equality
func == (lhs: ValueDictionary, rhs: ValueDictionary) -> Bool {
// Check if they have the same number of keys
guard lhs.count == rhs.count else { return false }
// Loop over the keys in lhs
for key in lhs.keys {
// Check if rhs has the same key and value as lhs
guard let value = rhs[key], value == lhs[key] else { return false }
}
// If all checks passed, return true
return true
}
// Define two arrays of dictionaries
let myMroducts: [ValueDictionary] = [
["name": .string("Apple"), "price": .number(9.99)],
["name": .string("Banana"), "price": .number(5.44)],
["name": .string("Sling Academy"), "price": .number(0.00)]
]
let yourProdcuts: [ValueDictionary] = [
["name": .string("Apple"), "price": .number(9.99)],
["name": .string("Banana"), "price": .number(5.44)],
["name": .string("Sling Academy"), "price": .number(0.00)]
]
if(myMroducts == yourProdcuts) {
print("I have the same products as you!")
} else {
print("We have different products!")
}
Output:
I have the same products as you!