Trouble with generic function in Swift 3

Question

with the premise that it's the first time I try to understand generic functions, I was wondering what is wrong with the following code (Swift 3):

func isTgreatherthanU<T: Comparable, U: Comparable>(t: T, u: U) -> Bool {
    return t > u
}

(I know it's a stupid function, but it's only meant to understand how to write generic code.)

The compiler says:

Binary operator '>' cannot be applied to operands of type 'T' and 'U'

I thought that, by declaring T and U as conforming to the Comparable protocol, the code should have worked, but I'm obviously doing something wrong... Any idea?


Show source
| generics   | function   | swift   2017-01-05 16:01 2 Answers

Answers to Trouble with generic function in Swift 3 ( 2 )

  1. 2017-01-05 16:01

    A value of a Comparable type can be compared with another value of the same type. In your case, T and U are unrelated and possibly different types. For example, you cannot compare a String with an Int even if both types are Comparable.

    What you want is

    func isTgreatherthanU<T: Comparable>(t: T, u: T) -> Bool {
        return t > u
    }
    

    i.e. both arguments are values of the same type T.

  2. 2017-01-05 16:01

    The Swift Standard Library only implements binary operators like > to compare two objects of the same type. T and U conform both to Comparable, but they might be of two different types. Swift considers T and U as different types, no matter which protocols they conform to.

    Only something like that would work:

    func isTgreatherthanU<T: Comparable>(t: T, u: T) -> Bool {
        return t > u
    }
    

Leave a reply to - Trouble with generic function in Swift 3

◀ Go back