为什么 Array.sorted() 没有默认关闭?
Why doesn't Array.sorted() have default closure?
给定以下游乐场片段
let list = [4.2, 1.3, 7.8]
let list1 = list.sorted() { [=11=] < }
let list2 = sorted(list)
let list3 = sorted(list) { [=11=] < }
我可以使用两种形式的自由函数 sorted
,带或不带闭包。但是 Array.sorted() 方法没有这样的机会。有充分的理由不这样做吗? Apple 不能这样声明吗?
func sorted(isOrderedBefore: (<T>, <t>) -> Bool = { [=12=] < }) { ...
(作为附带问题,为什么 playground 在右侧显示 (3 times)
,而不是 list1
和 list3
的结果列表?)
默认闭包仅在方法仅适用于符合 Comparable
协议的 T
时才可行。并非每种类型都定义了 <
或 >
运算符。
如果仔细观察,自由函数形式有两种形式。一份用于 T
,一份用于 T
,即 Comparable
.
在let list2 = sorted(list)
函数中
func sorted<C : SequenceType where C.Generator.Element : Comparable>(source: C) -> [C.Generator.Element]
被调用。此函数仅针对序列定义
元素类型为 Comparable
,即可以与 <
.
进行比较
另一方面,不可能定义数组扩展
方法 sorted()
仅适用于具有可比较元素的数组,
比较
- Array extension to remove object by value: "You cannot write a method on a generic type that is more restrictive on the template."
- Is it possible to make an Array extension in Swift that is restricted to one class?
给定以下游乐场片段
let list = [4.2, 1.3, 7.8]
let list1 = list.sorted() { [=11=] < }
let list2 = sorted(list)
let list3 = sorted(list) { [=11=] < }
我可以使用两种形式的自由函数 sorted
,带或不带闭包。但是 Array.sorted() 方法没有这样的机会。有充分的理由不这样做吗? Apple 不能这样声明吗?
func sorted(isOrderedBefore: (<T>, <t>) -> Bool = { [=12=] < }) { ...
(作为附带问题,为什么 playground 在右侧显示 (3 times)
,而不是 list1
和 list3
的结果列表?)
默认闭包仅在方法仅适用于符合 Comparable
协议的 T
时才可行。并非每种类型都定义了 <
或 >
运算符。
如果仔细观察,自由函数形式有两种形式。一份用于 T
,一份用于 T
,即 Comparable
.
在let list2 = sorted(list)
函数中
func sorted<C : SequenceType where C.Generator.Element : Comparable>(source: C) -> [C.Generator.Element]
被调用。此函数仅针对序列定义
元素类型为 Comparable
,即可以与 <
.
另一方面,不可能定义数组扩展
方法 sorted()
仅适用于具有可比较元素的数组,
比较
- Array extension to remove object by value: "You cannot write a method on a generic type that is more restrictive on the template."
- Is it possible to make an Array extension in Swift that is restricted to one class?