Generics in array extension method, with Comparable constraint can't be compared

Comparing two generic values with Comparable constraints causes Type mismatch compile error.

extension Swift.Array where T: Comparable {
    func compareItems(_ anItem1: T, _ anItem2: T) -> Int {
        
        if anItem1 < anItem2 {
            return -1
        }
        if anItem1 > anItem2 {
            return 1
        }
        return 0
    }
}

However, it compiles if I force cast it like this:

if (anItem1 as! Comparable) < (anItem2 as! Comparable) {
    return -1
}

This isn’t limited to Comparable, if I use where T: Int instead, I get the same result - error unless I force cast.

In Echoes forced cast as Comparable doesn’t compile, I have to force cast both items as Any.

However, even though it compiles when forced cast is used, it produces run time error.

Test project attached.

Since we had a similar conversation not long ago, I just want to make sure - is it possible to use Comparable and Equatable like this in Elements? My guess would be (maybe) no, but why are both interfaces defined in RO SwiftBaseLibrary? Are they just stubs or they can also be used? If so, how can they be used? Same as in XCode Swift?

Generics Comparable test.zip (40.3 KB)

I believe interfaces cant satisfy standard operators (yet), no.

1 Like