Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly compare tuples in Swift?

I do have 2 different tuples of type (Double, Double):

let tuple1: (Double, Double) = (1, 2) let tuple2: (Double, Double) = (3, 4) 

I want to compare their values using a simple if statement. Something like:

if (tuple1 == tuple2) {     // Do stuff } 

This throws the following error:

Could not find an overload for '==' that accepts the supplied arguments

My current solution is a function like this:

func compareTuples <T: Equatable> (tuple1: (T, T), tuple2: (T, T)) -> Bool {     return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1) } 

I already tried to write an extension but can't make it work for tuples. Do you have a more elegant solution to this problem?

like image 304
Git.Coach Avatar asked Jun 30 '14 09:06

Git.Coach


People also ask

Can we compare two tuples in Swift?

To compare tuples, just use the == operator, like this: let singer = ("Taylor", "Swift") let alien = ("Justin", "Bieber") if singer == alien { print("Matching tuples!") } else { print("Non-matching tuples!") }

How do you compare two tuples?

Rules for comparing tuplesCompare the n-th items of both tuple (starting with the zero-th index) using the == operator. If both are equal, repeat this step with the next item. For two unequal items, the item that is “less than” makes the tuple, that contains it, also “less than” the other tuple.

Are tuples Equatable Swift?

But you can't use the contains() method: a. contains((3, 4)) // no!

Is tuple comparison possible?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.


1 Answers

Update

As Martin R states in the comments, tuples with up to six components can now be compared with ==. Tuples with different component counts or different component types are considered to be different types so these cannot be compared, but the code for the simple case I described below is now obsolete.


Try this:

func == <T:Equatable> (tuple1:(T,T),tuple2:(T,T)) -> Bool {    return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1) } 

It's exactly the same as yours, but I called it ==. Then things like:

(1, 1) == (1, 1) 

are true and

(1, 1) == (1, 2) 

are false

like image 108
JeremyP Avatar answered Sep 20 '22 13:09

JeremyP