Consider a Generically constructed Node
for a DoublyLinkedList
:
public class Node<T> {
var value: T
var next: Node<T>?
weak var previous: Node<T>?
init(value: T) {
self.value = value
}
}
public class DoublyLinkedList<T> {
var head: Node<T>?
private var tail: Node<T>?
public func append(value: T) {
let newNode = Node(value: value)
if let tailNode = tail {
newNode.previous = tailNode
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
}
....
How do I make the DoublyLinkedList
even more Generic?
(i.e. I subclassed Node
so that I could implement some specific behaviors via inheritance). I can't seem to synthesize a DoublyLinkedList
of my subclass because it is looking for the "Concrete"? type of Node
class TransactionFilterNode: Node<Search> {
let seedTransactions: [Transaction]
init(search: Search, allTransactions: [Transaction]){
self.seedTransactions = allTransactions
super.init(value: search)
}
I can't seem to get this to be inserted or appended to DoublyLinkedList because DoublyLinkedList is looking for a Node
, not a subclass of Node
.
Edit: Solved
The solution was to pull the call for Node
into the function call parameter so that I could pass a subclassed version. See below.
CodePudding user response:
So your append
method expects a type T
(which in your case is Search
), while you are directly subclassing a Node
.
So you can
Option 1: create append
that accepts the Node
, e.g.:
func append(value: T) {
let newNode = Node(value: value)
append(newNode: newNode)
}
func append(newNode: Node<T>) {
if let tailNode = tail {
newNode.previous = tailNode
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
}
So now you can
let x = DoublyLinkedList<Search>()
let y = TransactionFilterNode(...)
x.append(newNode: y) // No problem
Option 2: subclass Search
instead of subclassing Node
I.e. maybe instead of class TransactionFilterNode: Node<Search>
you meant to say class TransactionFilter: Search
?