Can Comparable be generic?

Consider this structure:

struct Person : Comparable {
    let name: String
    let age: Int
}

extension Person {
    static func < (lhs: Person, rhs: Person) -> Bool {
        return lhs.name < rhs.name
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.age == rhs.age && lhs.name == rhs.name
    }
}

      

Person

Structures are now sorted by name.

But what if I want to be able to sort with name

or age

, is there a way to create a <

func generic?

+3


source to share


2 answers


You cannot create a general protocol. There are two ways to solve your problem:

You can create a wrapper structure that only contains the Person value, but sorted by a different combination of properties.



Alternatively, you could think of a way to compose methods that compare two things. We did this in an episode of Swift Talk: https://talk.objc.io/episodes/S01E19-from-runtime-programming-to-functions (if you don't want to watch the video, you can read the transcript).

+2


source


Try the following:



struct Person : Comparable {
    let name: String
    let age: Int
    let compareByAge: Bool
}

extension Person {
    static func < (lhs: Person, rhs: Person) -> Bool {
        if compareByAge {
            return lhs.age < rhs.age
        }
        return lhs.name < rhs.name
}

static func == (lhs: Person, rhs: Person) -> Bool {
    if compareByAge {
        return lhs.age == rhs.age
    }
    return lhs.name == rhs.name
}

      

+1


source







All Articles