Generic class that conforms to Comparable in Swift

前端 未结 2 603
耶瑟儿~
耶瑟儿~ 2021-01-02 18:37

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

相关标签:
2条回答
  • 2021-01-02 18:46

    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
    }
    
    0 讨论(0)
  • 2021-01-02 18:57

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题