gpt4 book ai didi

arrays - 使用闭包实现 sortInPlace 作为 MutableCollectionType 扩展

转载 作者:行者123 更新时间:2023-11-30 13:52:00 25 4
gpt4 key购买 nike

我正在尝试向 Card 添加两个方法数组,这样我就可以调用 cardArray.suitSort()cardArray.rankSort()执行sortInPlace({})括号之间具有适当的比较函数。但是,在编译以下代码时,我收到错误“对成员 sortInPlace 的模糊引用”,无论我是否保留 self.参加或不参加。

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)})每次我想对 Array<Card> 进行排序时?

最佳答案

我通过使用名为 CardCollection 的协议(protocol)和类似于以下内容的代码解决了这个困境:

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)
}
}

关于arrays - 使用闭包实现 sortInPlace 作为 MutableCollectionType 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34147505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com