Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
Swift 4 Conform Comparable protocol and sort method issue

I write following Struct that conform to 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)

It all works fine using > < == and sort too. but if I reverse sort method on array of records, It gives me output as follows:

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

Highest wins should come first followed by less wins but if wins are equal then less losses should come before more losses. Am I doing anything wrong here or missing something? I am still learning swift so might be possible.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

To order an array of stuff in the reverse sort order, you can just sort by >:

records.sort(by: >)

reverse will just reverse the array, without sorting it.

over 4 years ago · Santiago Trujillo Relatório

0

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

records.sort()
records.reverse()
over 4 years ago · Santiago Trujillo Relatório

0

There is also a universal way to sort however you want without conforming to Comparable protocol. It might be useful if you apply various sorting logic in different places or just do sorting infrequently. Try this one:

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

Note, how we can use non-trivial (yet efficient) predefined sorting algorithms for strings (from Foundation) such as 'localizedStandardCompare', 'localizedCompare' and etc.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda