简体   繁体   中英

Swift 4 Linked List Generic Types: Cannot compare two generic values

I am trying to implement a linked list in Swift playgrounds using generic types. My remove function is giving me errors about comparing to generic types, even though they are equivalent.

I have already tried conforming to the Equatable and Comparable protocols in my function declaration, but the errors still persist.

class Node<T> {

    var value:T
    var next:Node?

    init(value:T) {
        self.value = value
        self.next = nil
    }

}

func remove<T: Equatable>(value:T) -> Node<T>? {
    if isEmpty {
        return nil

    }
    else {
        var current = head!
        var prev:Node<T>? = nil

        while (current.value != value && current.next != nil) {
            prev = current
            current = current.next!
        }

        if (current.value == value) {
            //Found node. Remove by updating links, return node
            if let prev = prev {
                prev.next = current.next
                current.next = nil
            }
            else {
                self.head = current.next
                current.next = nil
            }

            size -= 1
            return current
        }
        else {
            return nil
        }
    }
}

On this line of my remove function:

while (current.value != value && current.next != nil) {

I am receiving the error:

Binary operator '!=' cannot be applied to operands of type 'T' and 'T'

Also when I conform to Equatable, I am receiving this error on the following line when trying to update the previous node:

Cannot assign value of type 'Node<T>' to type 'Node<T>?'

This error will disappear when I remove the Equatable protocol.

Any ideas? It sounds like I may be missing a simple step when conforming to the protocols, but I'm not sure what is missing... Thanks in advance!

The Equatable conformance should be added to the generic class itself also, not only for the function, like this:

class Node<T: Equatable > {
    // Your code here.
}

By saying current.value != value , you are trying to compare current.value with value . At this point the compiler is sure that value conforms to Equatable , but it is not sure wether current.value does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM