Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class that conforms to Comparable in Swift

I'm attempting to create a simple generic node class that conforms to the Comparable protocol so that I can easily compare nodes without accessing their key. When I attempt to write the < and == functions, however, the compiler doesn't seem to like it. The < and == functions expect a type when defining the Node parameters. This was simple in Java where you defined equality and < internally to the class. Swift asks for it globally. Any thoughts ?

Example:

func < (lhs:Node<E:Comparable>, rhs:Node<E:Comparable>) -> Bool {
    return lhs.key < rhs.key
}


func == (lhs:Node<E:Comparable>, rhs:Node<E:Comparable>) -> Bool {
    return lhs.key == rhs.key
}


class Node<D:Comparable>: Comparable {

    var key: D!
    var next:Node?
    var prev:Node?

    init( key:D ) {

        self.key = key
    }
}
like image 282
Daniel Rushton Avatar asked Jul 29 '14 21:07

Daniel Rushton


People also ask

How do I compare two generic types in Swift?

The Swift standard library defines a protocol called Equatable , which requires any conforming type to implement the equal to operator ( == ) and the not equal to operator ( != ) to compare any two values of that type. All of Swift's standard types automatically support the Equatable protocol.

How do you conform to comparable?

To add Comparable conformance to Date , first declare conformance to Comparable and implement the < operator function. This function uses the least specific nonmatching property of the date to determine the result of the comparison.

Is comparable a generic interface?

Comparable interface is a generic type. A String can be compared to other String. But not with objects of a different class. extends, when applied to type parameters, actually means “extends or implements.”


2 Answers

You're close! The Node class already specifies that for Node<D>, D must conform to Comparable. Therefore, Node<E: Comparable> in the decl for == and < is redundant. Instead, you want to restrict the types that the operators can be invoked upon:

func < <E: Comparable>(lhs: Node<E>, rhs: Node<E>) -> Bool {
    return lhs.key < rhs.key
}


func == <E: Comparable>(lhs: Node<E>, rhs: Node<E>) -> Bool {
    return lhs.key == rhs.key
}

class Node<D: Comparable>: Comparable {

    var key: D!
    var next: Node?
    var prev: Node?

    init(key: D) {
        self.key = key
    }
}
like image 74
Jack Lawrence Avatar answered Sep 22 '22 21:09

Jack Lawrence


You were very close. Small syntax issue Try this:

class Node<D:Comparable>: Comparable {

    var key: D!
    var next:Node?
    var prev:Node?

    init( key:D ) {

        self.key = key
    }

}

func < <E:Comparable> (lhs:Node<E>, rhs:Node<E>) -> Bool {
    return lhs.key < rhs.key
}

func == <E:Comparable> (lhs:Node<E>, rhs:Node<E>) -> Bool {
    return lhs.key == rhs.key
}
like image 39
hcanfly Avatar answered Sep 24 '22 21:09

hcanfly