我写了遵循协议(protocol) Comparable 的结构。struct Record: Comparable { static func < (lhs: Record, rhs: Record) -> Bool { if lhs.wins == rhs.wins { return lhs.losses > rhs.losses } return lhs.wins < rhs.wins } var wins: Int var losses: Int init(wins: Int, losses: Int) { self.wins = wins self.losses = losses }}var a1 = Record(wins: 3, losses: 8)var b1 = Record(wins: 3, losses: 9)var c1 = Record(wins: 4, losses: 7)var records = [a1, b1, c1]records.reverse()print(records)使用 > [__lldb_expr_48.Record(wins: 4, losses: 7), __lldb_expr_48.Record(wins: 3, losses: 9), __lldb_expr_48.Record(wins: 3, losses: 8)]最高的胜利应该先出现,然后是更少的胜利,但如果胜利相等,那么更少的损失应该在更多的损失之前。我在这里做错了什么或遗漏了什么?我仍在快速学习,所以可能是可能的。 最佳答案 要以相反的排序顺序对一组东西进行排序,您可以通过 sort > :records.sort(by: >)reverse 只会反转数组,而不对其进行排序。关于Swift 4 Conform Comparable 协议(protocol)和排序方法问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54762355/
10-11 22:32