Turnipdabeets
Turnipdabeets

Reputation: 6005

Swift Generic Type Equatable by sorting array

I'm trying to conform my generic CustomSet to Equatable but I get the following error when I try to sort the list array in the Equatable func:

Ambiguous reference to member '<'

I think the problem is that the compiler has no information on value types when comparing on sort, but I'm not sure how to tell it what it needs. Is this even possible to do on generic types?

The goal is to say CustomSet is Equal if list contains the exact same values.

struct CustomSet<T : Equatable> {
    var list: [T]
    init(_ list: [T]){
        self.list = list
    }
}

extension CustomSet : Equatable {
    static func == (lhs: CustomSet, rhs: CustomSet) -> Bool {
        return lhs.list.count == rhs.list.count && lhs.list.sorted(by: <) == rhs.list.sorted(by: <)
    }
}

Upvotes: 0

Views: 365

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

You need to restrict your generic type parameter to Comparable to be able to use the < operator on elements of list and hence sort list.

struct CustomSet<T : Comparable> {
    var list: [T]
    init(_ list: [T]){
        self.list = list
    }
}

Upvotes: 2

Related Questions