Sequence types such as Array
do not currently conform to Comparable
, which means this code is valid:
let items1 = (1, 2, 3)
let items2 = (4, 5, 6)
print(items1 < items2)
But this is not:
let items3 = [1, 2, 3]
let items4 = [4, 5, 6]
print(items3 < items4)
(One minor wrinkle: print([1, 2, 3] < [4, 5, 6])
is valid today, but only if you import Foundation thanks to IndexPath
. This started a debate with my kid, and now I'm here…)
I'd like to propose adding an extension to Sequence
to use the built-in lexicographicallyPrecedes()
method to make that second code sample valid, like this:
extension Sequence where Element: Comparable {
public static func <(lhs: Self, rhs: Self) -> Bool {
lhs.lexicographicallyPrecedes(rhs)
}
}
We could then manually conform specific types such as array to Comparable
:
extension Array: Comparable where Element: Comparable { }
My thinking here is that we already support Comparable
for tuples, strings, and IndexPath, so there's a fair chunk of Swift precedent for this behavior. Such a feature also appears standard in other languages such as Rust, Python, Ruby, etc.
I've chosen Sequence
because it matches the availability of the lexicographicallyPrecedes()
method.
All input welcome. Thank you!