Swift “ambiguous use of operator '>'”

http://stackoverflow.com/questions/25458548/swift-ambiguous-use-of-operator

 

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 documentationhttps://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-XID_152

Any ideas?

share improve this question
 
   
What is names defined as? –  Mike S Aug 23 '14 at 4:51
   
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 Aug 23 '14 at 5:20 
2 
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 Aug 23 '14 at 14:13
   
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. –  wottpal Aug 23 '14 at 22:25 

2 Answers

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 })

share improve this answer
 

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 } )
share improve this answer
 

Your Answer

转载于:https://www.cnblogs.com/xuejinhui/p/4618182.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值