Use tuples to sort Comparable objects based on multiple properties.
Example: sorting contacts by surname; then by name, to see all names from the same family in a row.struct Person {
let name: String
let surname: String
}
extension Person: Comparable {
static func < (lhs: Person, rhs: Person) -> Bool {
// Compare tuples instead of properties 😉
(lhs.surname, lhs.name) < (rhs.surname, rhs.name)
}
}
extension Person: CustomStringConvertible {
var description: String { "\(name) \(surname)" }
}
let names = [
Person(name: "Zelda", surname: "Appleseed"),
Person(name: "Donald", surname: "Stevens"),
Person(name: "John", surname: "Appleseed"),
Person(name: "Steven", surname: "Appleseed"),
Person(name: "Michael", surname: "Bowden")
]
print(names.sorted())
/* prints:
[
"John Appleseed",
"Steven Appleseed",
"Zelda Appleseed",
"Michael Bowden",
"Donald Stevens"
]
*/