Ambiguous use of operator '>'

Viewed 1103

i tried this

simple2 = {s1, s2 in s1 > s2}

and

var simple2 = {$0 > $1}

but still showing me

swift 3 closure Ambiguous use of 'operator >'

2 Answers

The closure must explicitly declare the type of the s1 and s2 parameters and that type must implement > operator. The typical way to do that is to make the signature of that closure ensure that the two parameters are (a) the same type; and (b) conform to the Comparable protocol.

If you want simple2 to take any Comparable type, rather than a closure, you could define a generic function:

func simple2<T: Comparable>(_ s1: T, _ s2: T) -> Bool {
    return s1 > s2
}

Then you could call it with any Comparable type.

You need to specify the types of s1 and s2 and $0 and $1. Not even a human can infer what type you want these to be of, let alone the Swift compiler.

> can be applied to multiple types. Here are some of the examples:

  • Int and Int
  • Double and Double
  • CGFloat and CGFloat

You can specify the types like this:

let simple2: (Int, Int) -> Bool = {$0 > $1}
Related