Compare two tuples for equality in Swift


Swift allows us to compare two tuples for equality up to arity six using the simple == operator. Arity six means tuples with more than six elements can not be compared in this way.

Now see the example code below where we are comparing two tuples using the == operator and if... else statement:

let colors = ("Green", "Yellow", "Violet")
let fruits = ("Apple", "Mango", "Lychee")

if colors == fruits {
    print("Tuple matched")
} else {
    print("Tuple did not matched")
}

Output:

Tuple did not matched

If we run the above code, it will run the code inside the else statement as the two tuples are not equal.

Note that, if the two tuples don’t have the same number of elements, then we can not compare them with this method.

Comparing two tuples with element names

If the elements of a tuple have names, then these names will not be evaluated when we compare the two tuples.

See the example below:

let employees = ("Armin", "Mikasha")
let students = (name1: "Armin", name2: "Mikasha")

if employees == students {
    print("Tuple matched")
} else {
    print("Tuple did not matched")
}

Output:

Tuple matched

As you can see, the two tuples matched even though the first tuple has no element names and the second tuple has element names.

The result will be the same even if there are element names in both the tuples and each name are different you can see below:

var employees = (employee1: "Armin", employee2: "Mikasha")
var students = (name1: "Armin", name2: "Mikasha")

if employees == students {
    print("Tuple matched")
} else {
    print("Tuple did not matched")
}

Output:

Tuple matched

You can see that our tuples matched even though the names did not match for the two tuples.


So what did we learn from this tutorial?

We have learned how to compare two Swift tuples using the if...else statement.