当前位置 : 主页 > 手机开发 > 其它 >

Swift 4 Conform Comparable协议和排序方法问题

来源:互联网 收集:自由互联 发布时间:2021-06-11
我编写符合协议Comparable的以下Struct. 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 in
我编写符合协议Comparable的以下Struct.

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)

使用>一切正常< ==并排序.但如果我在记录数组上反转sort方法,它给我输出如下:

[__lldb_expr_48.Record(wins: 4, losses: 7), __lldb_expr_48.Record(wins: 3, losses: 9), __lldb_expr_48.Record(wins: 3, losses: 8)]

应该先取得最高胜利,然后取得较少的胜利,但如果胜利相等,那么在损失增加之前应该减少损失.我在这里做错了什么或遗漏了什么?我仍然学得很快,所以可能.

要按反向排序顺序排序一系列东西,您可以按>排序:

records.sort(by: >)

反向将只是反转数组,而不进行排序.

网友评论