Swift - Testing Arrays for Equality

Introduction

You can test the equality of two arrays using the == operator.

Two arrays are equal if they contain exactly the same elements and in exactly the same order.

Consider the following example:

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

These two arrays are not equal, as they do not have the same number of elements:

print("Equal: \(array1 == array2)")  //false

Now append another element to array2 :

array2.append (5)

These two arrays are now equal, as they do have the same number of elements in the same exact order:

print("Equal: \(array1 == array2)")  //true

Suppose you have another array:

var array3 =  [5,1,2,3,4]

It is not equal to array1 because the order of the elements is not the same:

print("Equal: \(array1 == array3)")  //false

Related Topic