Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

generics

swift

Xcode is complaining that it "Cannot assign value of type Node to type Node<_>?" in lines 23,24,26,27 (the assignments of 'node' to 'top' and 'bottom' in the conditional portion of enqueue). I'm not sure what this means, and why Xcode sees a difference in the types of the node and top / bottom

class Node<T> {
    var key: T?
    weak var next: Node<T>?
    weak var previous: Node<T>?

    init(key: T, previous: Node? = nil) {
        self.key = key
        self.previous = previous
    }
}


class Dequeue<T> {
    private var count: Int = 0
    private weak var top: Node<T>?
    private weak var bottom: Node<T>?

    func enqueue<T>(val: T) {
       // if dequeue is empty
       let node = Node<T>(key: val)

        if top == nil {
            self.top = node
            self.bottom = node
        } else {
            self.bottom?.next = node
            self.bottom = node
        }
     }

}
like image 232
TravMatth Avatar asked Nov 27 '15 04:11

TravMatth


1 Answers

Remove the generic <T> from the method declaration.

class Dequeue<T> {
    ...

    func enqueue(val: T) {
        ...
     }    
}

The <T> in the class declaration applies to the entire class, including method bodies. The explicit <T> on the method body introduces a new generic type T that shadows the class's T type; since it is independent of the global T, the compiler can't ensure they are compatible.

like image 158
Kevin Avatar answered Nov 01 '22 07:11

Kevin