Generic class that conforms to Comparable in Swift

喜你入骨 提交于 2019-11-29 19:54:10

问题


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
    }
}

回答1:


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
    }
}



回答2:


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
}


来源:https://stackoverflow.com/questions/25025618/generic-class-that-conforms-to-comparable-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!