快速游乐场中单表达式闭包的隐式返回

Kev*_*nle 4 swift

根据Apple的Swift书,而不是

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversed = sorted(names, { s1, s2 in return s1 > s2 })
Run Code Online (Sandbox Code Playgroud)

因为闭包的主体包含一个返回Bool 的单个表达式s1> s2,所以没有歧义,因此可以省略return关键字:

reversed = sorted(names, { s1, s2 in s1 > s2 })
Run Code Online (Sandbox Code Playgroud)

嗯,这在Playground中不起作用.Playground中的错误表示不明确使用运算符'>'.

更新:同样,这个

reversed = sorted(names, { $0 > $1 })
Run Code Online (Sandbox Code Playgroud)

不起作用.同样的错误.这个

reversed = sorted(names, { return $0 > $1 })
Run Code Online (Sandbox Code Playgroud)

确实.

更新2:在看到Mike S的回答后,我确信该错误可能是由于Swift String和NSString.我试过了

let nums = [3, 5, 1, 2, 10, 9]
var dec = sorted(nums, { n1, n2 in n1 > n2 })
var inc = sorted(nums, { n1, n2 in n1 < n2 })
Run Code Online (Sandbox Code Playgroud)

他们都使用或不使用import语句.解决String的问题并不坏,因为现在我们只需要在使用>运算符比较String时输入return.

那么这里可以解释什么(没有检查正常项目)?

Mik*_*e S 5

这里的问题实际上是比较Strings.一个ArrayInt作品只是无论是罚款<还是>运营商,但有一个ArrayStringsS,只有<运营商将工作(如Xcode的6.1 GM的反正).

要表明这是一个String比较问题,请在Playground中尝试:

import Foundation
let result1 = "Chris" < "Alex" // false
let result2 = "Chris" > "Alex" // error: ambiguous use of operator '>'
Run Code Online (Sandbox Code Playgroud)

如果您打开Playground的控制台输出,您还会看到:

Playground execution failed: <EXPR>:17:9: error: ambiguous use of operator '>'
"Chris" > "Alex"
        ^
Foundation.>:1:6: note: found this candidate
func >(lhs: String, rhs: NSString) -> Bool
     ^
Foundation.>:1:6: note: found this candidate
func >(lhs: NSString, rhs: String) -> Bool
Run Code Online (Sandbox Code Playgroud)

所以,这个问题似乎是在编译过程很难确定是否"Chris""Alex"StringS或NSString秒.

此外,如果你取出importPlayground顶部的默认语句,一切都会正常工作,因为NSString没有导入,因此,没有桥接到String:

let result1 = "Chris" < "Alex" // false
let result2 = "Chris" > "Alex" // true
Run Code Online (Sandbox Code Playgroud)

或者,使用问题中的代码(否import):

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversed = sorted(names, { $0 > $1 }) // [Alex, Barry, Chris, Daniella, Ewa]
Run Code Online (Sandbox Code Playgroud)

但是我无法回答的是,如果你在传递给的闭包中使用一个语句,那么> 它的确有效.returnsorted