Use Comparable Protocol in Swift
Written by Team Kodeco
The Comparable protocol in Swift is used to define a sort order for instances of a type. It requires that you implement a single operator function called < that returns a Bool indicating whether the first value should be considered less than the second.
By implementing Comparable, a type can be used as the key type in a dictionary or the element type in a sorted array. The protocol also provides default implementations for the ==, >, >=, <=, and != operators, which are based on the implementation of the < operator.
Here is an example implementation of the Comparable protocol for a custom type Person:
struct Person: Comparable {
let firstName: String
let lastName: String
static func < (lhs: Person, rhs: Person) -> Bool {
if lhs.lastName != rhs.lastName {
return lhs.lastName < rhs.lastName
} else {
return lhs.firstName < rhs.firstName
}
}
}
let person1 = Person(firstName: "Amy", lastName: "Smith")
let person2 = Person(firstName: "Zoe", lastName: "Smith")
person1 < person2 // true