How to elegantly compare tuples in Swift?
I agree that this behavior is not expected, since tuples can be compared in diverse languages such as Python and Haskell, but according to the official documentation:
NOTE
Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information, see Classes and Structures.
So, this might be the Swift equivalent of "you're holding the phone wrong," but by current guidelines, the idiomatic way to do this is to define a Class or Struct (or even an Enum) with a Comparable implementation to provide ==
and related operators.
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