簡體   English   中英

Swift 4鏈表通用類型:無法比較兩個通用值

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

我正在嘗試使用泛型類型在Swift游樂場中實現一個鏈表。 我的刪除功能給我有關與泛型類型進行比較的錯誤,即使它們是等效的。

我已經在函數聲明中嘗試符合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
        }
    }
}

在我的刪除功能的這一行:

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

我收到錯誤:

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

同樣,當我符合Equatable時,嘗試更新前一個節點時,也會在下一行收到此錯誤:

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

當我刪除Equatable協議時,此錯誤將消失。

有任何想法嗎? 聽起來好像我在遵循協議時可能會錯過一個簡單的步驟,但是我不確定會丟失什么...在此先謝謝您!

不僅要為函數添加Equatable一致性,還應將其添加到泛型類本身,如下所示:

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

通過說current.value != value ,您正在嘗試將current.valuevalue進行比較。 在這一點上,編譯器確定value符合Equatable ,但是不確定current.value是否符合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM