简体   繁体   English

Swift 4链表通用类型:无法比较两个通用值

[英]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. 我正在尝试使用泛型类型在Swift游乐场中实现一个链表。 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. 我已经在函数声明中尝试符合Equatable和Comparable协议,但是错误仍然存​​在。

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: 同样,当我符合Equatable时,尝试更新前一个节点时,也会在下一行收到此错误:

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

This error will disappear when I remove the Equatable protocol. 当我删除Equatable协议时,此错误将消失。

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: 不仅要为函数添加Equatable一致性,还应将其添加到泛型类本身,如下所示:

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

By saying current.value != value , you are trying to compare current.value with value . 通过说current.value != value ,您正在尝试将current.valuevalue进行比较。 At this point the compiler is sure that value conforms to Equatable , but it is not sure wether current.value does. 在这一点上,编译器确定value符合Equatable ,但是不确定current.value是否符合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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