3
votes

I have just downloaded Xcode6-beta6. I am getting compiler error "ambiguous use of operator '>'" for following codes

reversed = sorted(names, { s1, s2 in s1 > s2 } )

It was working before in Xcode6-beta5.

The code is from apple swift documentation https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-XID_152

Any ideas?

2
What is names defined as?Mike S
What type is names? I just tried it successfully in a playground with the following code: let names = ["a", "b"]; let reversed = sorted(names, { s1, s2 in s1 > s2 } )Gary Makin
After seeing your comment i tested again and found the issue. Thanks. It's the issue with variable. In the swift document "reversed" was declared once and then used in everywhere and then this issue arises only for "Implicit Returns from Single-Expression Closures" and "Shorthand Argument Names" cases. If you define new variable or constant then this error does not show up.Moin Uddin
I get the same error with var arrayToSort = ["a", "b"]; arrayToSort.sort{ $0 > $1 }. If I change the operator to less than (<) the error disappears.zoma

2 Answers

5
votes

I had the same issue also with

if ("aa" > "bb")  {
    [...]
}

and

reversed = sorted(names, { $0 > $1 })

Apparently XCode can't correctly infer the correct type "String" for the parameters, thus creating an ambiguity on the operator. My solution has been to explicitly declare the type at least one of them which also makes the code more readable. Like in:

if ("aa" as String > "bb")  {
    [...]  
}

reversed = sorted(names, { $0 as String > $1 })

2
votes

This seems to be a bug in the Foundation framework's bridging. It declares overrides of > to handle comparing a String with an NSString and an NSString and a String, but those appear (in some cases) to conflict in matching. You can get around it (for some reason) by altering your syntax a little:

reversed = sorted(names, { s1, s2 in return s1 > s2 } )