Learning Time : 1h 15min
My Github : Bucket List Source Code
Example
struct User: Identifiable {
let id = UUID()
let firstName: String
let lastName: String
}
let users = [
User(firstName: "Arnold", lastName: "Rimmer"),
User(firstName: "Kristine", lastName: "Kochanski"),
User(firstName: "David", lastName: "Lister"),
].sorted {
$0.lastName < $1.lastName
}
Comparable
Comparable | Apple Developer Documentation
Swift provides the Comparable
protocol, which allows custom types to define their own sorting behavior.
Example, the User
struct represents a user with a first name and a last name.
We want to sort an array of User
objects based on their last names.
Comparable
protocol<
operator function, comparing the lastName
property of two User
instances.lhs
parameter represents the left-hand side of the comparison, and rhs
represents the right-hand side.true
if lhs
's last name comes before rhs
's last name, ensuring the array is sorted in ascending order of last names.struct User: Comparable {
let firstName: String
let lastName: String
static func < (lhs: User, rhs: User) -> Bool {
return lhs.lastName < rhs.lastName
}
}