Tuples in Swift seem to conform to Comparable inasmuch as I get these results:
print ( (3,0) < (2,10000) ) // false
print ( (0,0,5) < (0,0,7) ) // true
It seems to do a left-right member-by-member comparison of the tuples: it compares the first tuple members against each other, then the 2nd, and so on, until it finds a pair that are nonequal, and returns whether the first member of that pair is less than the second. Very sensible.
It even works with tuples that contain multiple types, as long as they are comparable, and as long as the two tuples being compared are of the same type:
print( ("a",4) < ("b",3) ) // true
So why does this give an error?
print ( [(1,2),(0,2)].max() ) ⛔️ Type '(Int, Int)' cannot conform to 'Comparable'
Thinking that maybe it would help if I declared the types explicitly, I tried:
typealias IntPair = (Int,Int)
let a: IntPair = (0,1)
let b: IntPair = (0,2)
let array: [IntPair] = [a,b]
print(array.max()) ⛔️ Type '(Int, Int)' cannot conform to 'Comparable'
My only conclusion is that the static function < is defined on tuples of the same type, whose components are all Comparable, but those tuples nonetheless do not conform to Comparable. But that doesn't seem very likely.
Does anyone know why max() does not work on arrays of tuples of the same type whose arguments are all Comparable?
Nope! Only nominal ("named") types can conform to protocols, which excludes tuples.
The standard library just happens to define
<operators for tuples up to 6 elements.