gionti
gionti

Reputation: 96

Trouble with generic function in Swift 3

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?

Upvotes: 2

Views: 218

Answers (2)

FelixSFD
FelixSFD

Reputation: 6092

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
}

Upvotes: 2

Martin R
Martin R

Reputation: 539685

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.

Upvotes: 4

Related Questions