According to THE Swift book from Apple, instead of
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversed = sorted(names, { s1, s2 in return s1 > s2 })
because the closure's body contains a single expression s1 > s2 that returns a Bool, there is no ambiguity, so the return keyword can be omitted:
reversed = sorted(names, { s1, s2 in s1 > s2 })
Well, this does not work in Playground. The error in Playground says Ambiguous use of operator '>'.
Update: Similarly, this
reversed = sorted(names, { $0 > $1 })
does not work. Same error. This
reversed = sorted(names, { return $0 > $1 })
does.
Update 2: After seeing Mike S's answer, I am convinced the bug might be due to Swift String and NSString. I tried
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 })
They all worked with or without the import statement. The work around for String is not to bad since now we just have to type return when we want to compare String using the > operator.
So what can be the explanation here (have not checked in a normal project)?
<
operator. – Mike S Oct 8 '14 at 6:01