1

given the following playground fragment

let list = [4.2, 1.3, 7.8]
let list1 = list.sorted() { $0 < $1 }
let list2 = sorted(list)
let list3 = sorted(list) { $0 < $1}

I can use two forms of the free function sorted, with or without the closure. But there is no such opportunity with the Array.sorted() method. Is there a good reason why not? Couldn't Apple have declared it as such?

func sorted(isOrderedBefore: (<T>, <t>) -> Bool = { $0 < $1 }) { ...

(As a side question, why does the playground show (3 times) on the right side, instead of the resultant list for list1 and list3?)

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • 1
    One concise alternative: `let list4 = list.sorted(<)` – Rob May 02 '15 at 00:12
  • 1
    @Rob: Your simple comment actually caused a serious light bulb to light up for me. Almost worth more than the answer I granted below. Thank you so much. – Travis Griggs May 05 '15 at 00:08

2 Answers2

5

In let list2 = sorted(list) the function

func sorted<C : SequenceType where C.Generator.Element : Comparable>(source: C) -> [C.Generator.Element]

is called. This function is only defined for sequences for which the element type is Comparable, i.e. can be compared with <.

On the other hand, it is not possible to define an array extension method sorted() which applies only to arrays with comparable elements, compare

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
4

A default closure would only be viable if the method only worked for T that conforms to the Comparable protocol. Not every type has the < or > operators defined.

If you look closely, the free function form comes in two flavors. One for all T, and one for T that are Comparable.

Kaan Dedeoglu
  • 14,765
  • 5
  • 40
  • 41
  • But wouldn't the compiler be able to note that the default wasn't going to work for the receiver type and yell at you? – Travis Griggs May 01 '15 at 22:53
  • Or put another way maybe, if I attempt to `sort()` T's that aren't `Comparable`, the compiler will chose the "needs closure" one and yell at me if I don't provide a closure. I'm unclear why it can't do that in this case as well. – Travis Griggs May 01 '15 at 22:55
  • 1
    A generic type on T cannot have a method that restricts T further, i.e Array cannot have a method that operates only on , I find it mildly annoying actually. – Kaan Dedeoglu May 01 '15 at 22:57