Arrays 使用闭包作为MutableCollectionType扩展实现sortInPlace
我正在尝试向Arrays 使用闭包作为MutableCollectionType扩展实现sortInPlace,arrays,swift,sorting,Arrays,Swift,Sorting,我正在尝试向Card数组中添加两个方法,以便调用cardArray.suitesort()或cardArray.rankSort()来执行sortInPlace({}),并在括号之间使用适当的比较函数。但是,在编译下面的代码时,无论我是否将self.部分保留,我都会遇到错误“对成员sortInPlace的模糊引用” extension MutableCollectionType where Generator.Element == Card { mutating func suitSor
Card
数组中添加两个方法,以便调用cardArray.suitesort()
或cardArray.rankSort()
来执行sortInPlace({})
,并在括号之间使用适当的比较函数。但是,在编译下面的代码时,无论我是否将self.
部分保留,我都会遇到错误“对成员sortInPlace的模糊引用”
extension MutableCollectionType where Generator.Element == Card {
mutating func suitSort() {
self.sortInPlace({SuitSorted($0,$1)})
}
mutating func rankSort() {
self.sortInPlace({RankSorted($0,$1)})
}
}
我如何才能让它工作,所以我不必每次对
数组进行排序时都使用sortInPlace({comparisonFunction($0,$1)})
?我通过使用一个名为CardCollection的协议和一些类似于以下的代码解决了这个难题:
protocol CardCollection : RangeReplaceableCollectionType, CustomStringConvertible {
var collective : [Card] { get set }
}
extension CardCollection {
mutating func shuffleInPlace() {
collective.shuffleInPlace()
}
// This is where the generic sorter takes place
mutating func sortInPlace(sortFun: (Card, Card) -> Bool?=DisplaySorted) {
collective.sortInPlace({sortFun($0,$1)!})
}
mutating func sortBySuit() {
sortInPlace(SuitSorted)
}
mutating func sortByRank() {
sortInPlace(RankSorted)
}
mutating func sortForDisplay() {
sortInPlace(DisplaySorted)
}
}