Home > database >  Swift: binary operator '<' cannot be applied to two 'Comparable' operands
Swift: binary operator '<' cannot be applied to two 'Comparable' operands

Time:06-15

I have a protocol defined that has within it a function that returns an associated type that the user can define in their protocol implementation. The only requirement is that the associated type conform to Comparable.

I have another class that uses elements that conform to this protocol. The issue I'm running into is that the compiler is complaining that I can't compare elements of the associated type, even though I've specifically marked them as Comparable in the protocol definition. Anyone see what I'm doing wrong here?

protocol MyElement {

    associatedtype T : Comparable
    func getValue() -> T

}

class MyNode {

    init(elements:[any MyElement]) {
    
        // Sort the elements
        let sortedElements = elements.sorted(by: { ( a:any MyElement, b:any MyElement ) -> Bool in
            let aT = a.getValue()
            let bT = b.getValue()
        
            return aT < bT
        })
    
    }

}

The compiler complains at the line aT < bT:

binary operator '<' cannot be applied to two 'Comparable' operands

CodePudding user response:

The < operator applies to two values of a single type that conforms to Comparable — not to two things designated merely as Comparable. A protocol does not conform to itself.

The use of any with MyElement doesn't affect this basic fact about the Comparable-constrained generic placeholder T. Since MyElement is generic over T, we would have to know that the two different MyElement-conforming objects you propose to sort resolve their T to the same type as one another — and in the code you wrote, we don't know that, so the compiler balks.

  • Related