为 CollectionType(数组)添加排序功能
Add Sorting Function to CollectionType (Arrays)
我想将自己的排序功能添加到数组中,因此我正在尝试扩展 CollectionType 协议以添加此功能。
这是我目前所拥有的:
extension CollectionType where Generator.Element : Comparable, Index : IntegerType{
func psoInsertionSort(){
var key: Generator.Element
var x, y: Int
for (x = 0; x < self.count; x++){
key = self[x]
for (y = x; y >= 0; y--){
if key < self[y]{
self.removeAtIndex(y+1)
self.insert(key, atIndex: y)
}
}
}
}
}
我需要将 CollectionType 中的元素约束为 Comparable 才能进行实际排序,我相信那里没有问题。
我遇到的问题是在 for 循环参数中:
for (x = 0; x < self.count; x++){
Binary operator '<' cannot be applied to operands of type 'Int' and
'Self.Index.Distance'
看起来 self.count 是 Self.Index.Distance 类型,老实说,我什至不确定它是否与 Self.Index.
类型相同
您只需将这些添加为协议要求即可。因此,您可以要求索引距离 是 Int
:
Index.Distance == Int
或者您可以更改循环条件:
for (var x = self.startIndex; x < self.endIndex; x++){
(您还需要在此处将协议要求更改为 Index == Int
,并删除之前的 var x
声明)
或者,属性 集合类型正是您在该循环中寻找的:
for x in self.indices
此外,您的函数 removeAtIndex
和 insert
不仅需要 CollectionType
,还需要 RangeReplaceableCollectionType
.
并且功能需要标注mutating
我想将自己的排序功能添加到数组中,因此我正在尝试扩展 CollectionType 协议以添加此功能。 这是我目前所拥有的:
extension CollectionType where Generator.Element : Comparable, Index : IntegerType{
func psoInsertionSort(){
var key: Generator.Element
var x, y: Int
for (x = 0; x < self.count; x++){
key = self[x]
for (y = x; y >= 0; y--){
if key < self[y]{
self.removeAtIndex(y+1)
self.insert(key, atIndex: y)
}
}
}
}
}
我需要将 CollectionType 中的元素约束为 Comparable 才能进行实际排序,我相信那里没有问题。
我遇到的问题是在 for 循环参数中:
for (x = 0; x < self.count; x++){
Binary operator '<' cannot be applied to operands of type 'Int' and 'Self.Index.Distance'
看起来 self.count 是 Self.Index.Distance 类型,老实说,我什至不确定它是否与 Self.Index.
类型相同您只需将这些添加为协议要求即可。因此,您可以要求索引距离 是 Int
:
Index.Distance == Int
或者您可以更改循环条件:
for (var x = self.startIndex; x < self.endIndex; x++){
(您还需要在此处将协议要求更改为 Index == Int
,并删除之前的 var x
声明)
或者,属性 集合类型正是您在该循环中寻找的:
for x in self.indices
此外,您的函数 removeAtIndex
和 insert
不仅需要 CollectionType
,还需要 RangeReplaceableCollectionType
.
并且功能需要标注mutating