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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With