为什么有些表达式记录结果而其他表达式只显示迭代计数?

Why do some expressions log results and others just show iteration counts?

Swift 我没怎么用过 playgrounds。大多数情况下我一直在项目中使用它,所以我在处理 playgrounds 时有点不知所措。

我在一个小操场上得到了这个测试代码:

let array = [7, 3, 4, 9, 2, 12, 5]
let firstSorted = array.sorted(<)
let secondSorted = sorted(array, <)
let thirdSorted = array.sorted { [=10=] <  }

右侧显示的输出显示了 firstSorted 和 secondSorted 旁边的排序数组输出。然而,thirdSorted 旁边的输出只是说(15 次)。

为什么?以及如何在不添加单独的 println 命令来记录输出的情况下查看输出?

第三种形式有一个尾随闭包,其参数由它们的位置指定。

另外两个是更短的形式,只采用比较运算符,恰好与所需闭包的签名相匹配。

另一个问题:(这次是关于语言,而不是游乐场)为什么 sorted(array, <)array.sorted(<) 形式都有效?第一种是一个全局函数,它有两个参数,第二种形式是数组 class 上的方法。

这是因为您传递给 sorted 的闭包被 sorted 调用以在对数组排序时进行 13 次元素比较,加上对 sorted 本身的调用。只要你写的一行代码在 playground 中是 运行,它就会显示表达式的结果或计数。因为同一行被计算了多次,所以 IDE 不能显示所有内容,所以它只显示计数。

如果你把它分成多行,你可以看到sorted的结果,以及[=17=] < 的13次评估的结果:

我想 IDE 可能会采用最外层结果最有趣的方法,并显示这一点,但这可能会隐藏您的闭包被多次调用的信息。

关于第二个问题:sorted 的全局双参数版本更通用。它对任何类型的序列进行排序:

// they should probably rename this placeholder to S...
func sorted<C : SequenceType>
  (source: C, isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool) 
  -> [C.Generator.Element]

所以你可以传入任何符合SequenceType:

的东西
// results in [4,3,2,1,0]
sorted(0..<5, >)  

// results in [(3,"bob"),(2,"fred")] because dictionary’s 
// SequenceType representation is unordered pairs
sorted([2:"fred",3:"bob"]) { [=11=].1 < .1 }

此外,由于全局函数可以根据受限输入进行重载,因此如果输入序列的元素为 Comparable:

,则可以有一个根本不需要比较器的重载版本
func sorted<C : SequenceType where C.Generator.Element : Comparable>
  (source: C) -> [C.Generator.Element]