Learning Time : 1h 15min

My Github : Bucket List Source Code

My Note index link

day68.png

KeyWords

Adding conformance to Comparable for custom types

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.

struct User: Comparable {
    let firstName: String
    let lastName: String
    
    static func < (lhs: User, rhs: User) -> Bool {
        return lhs.lastName < rhs.lastName
    }
}