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

时间:2019-02-19 09:03:46

标签: swift sorting

我写以下符合协议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)

使用> <==都可以正常工作,并且也可以排序。但是如果我对记录数组进行反向排序,它会给我输出如下:

  

[__ lldb_expr_48.Record(获胜:4,损失:7),__lldb_expr_48.Record(获胜:3,损失:9),__lldb_expr_48.Record(获胜:3,损失:8)]

最高的胜利应该首先出现,然后是更少的胜利,但是如果胜利是相等的,那么更少的损失就应该出现在更多的损失之前。我在这里做错什么还是错过了什么吗?我仍在学习敏捷,因此可能。

3 个答案:

答案 0 :(得分:4)

要按相反的排序顺序排列一组东西,您可以// Callback defined outside the class. function callback(event) { this.doSomething(); } class Foo { constructor(cb) { // Important: You have to bind it. this.cb = cb.bind(this); this.functionA(); } functionA() { let el = document.getElementById('element1'); el.addEventListener('click', this.cb); } functionB() { let el = document.getElementById('element1'); el.removeEventListener('click', this.cb); } doSomething() { console.log('doing something...'); } } const foo = new Foo(callback); // foo.functionB();<button id="element1"> Click here </button>

sort

>只会反转数组,而不对其进行排序。

答案 1 :(得分:1)

You just don't sort your array before you reverse it

records.sort()
records.reverse()

答案 2 :(得分:0)

还有一种通用的排序方法,但是您不符合可比较协议。如果您在不同位置应用各种排序逻辑或不经常进行排序,则可能会很有用。试试这个:

struct SimpleRecord {
    var wins: Int
    var losses: Int
    var name: String
    // we get a simple init for free
}

let a = SimpleRecord(wins: 3, losses: 8, name: "abc")
let b = SimpleRecord(wins: 3, losses: 9, name: "some ")
let c = SimpleRecord(wins: 4, losses: 7, name: "abc")
let d = SimpleRecord(wins: 3, losses: 8, name: "Abc")

var simpleRecords = [a, b, c, d]

simpleRecords.sort(by: { (lhs, rhs) -> Bool in
    if lhs.wins > rhs.wins {
        return true
    } else if lhs.wins == rhs.wins {
        if lhs.losses < rhs.losses {
            return true
        } else if lhs.losses == rhs.losses {
            return (lhs.name.localizedStandardCompare(rhs.name) == ComparisonResult.orderedDescending)
        } else {
            return false
        }
    } else {
        return false
    }
})

// print(simpleRecords) // it is a lazy collection so print is a bit messy
simpleRecords.forEach{ print($0) }

请注意,我们如何对字符串(来自Foundation)使用非平凡(尚未有效)的预定义排序算法,例如'localizedStandardCompare','localizedCompare'等。