Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

records.sort()
records.reverse()
over 4 years ago · Santiago Trujillo Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda