考慮為 a 一般構造Node的 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
}
....
如何使DoublyLinkedList更通用?
(即我進行了子類Node化,以便我可以通過繼承實作一些特定的行為)。我似乎無法合成DoublyLinkedList我的子類,因為它正在尋找“混凝土”?型別Node
class TransactionFilterNode: Node<Search> {
let seedTransactions: [Transaction]
init(search: Search, allTransactions: [Transaction]){
self.seedTransactions = allTransactions
super.init(value: search)
}
我似乎無法將其插入或附加到 DoublyLinkedList,因為 DoublyLinkedList 正在尋找 .Node而不是Node.
編輯:已解決
解決方案是將呼叫拉到Node函式呼叫引數中,以便我可以傳遞子類版本。見下文。
uj5u.com熱心網友回復:
因此,您的append方法需要一個型別T(在您的情況下是Search),而您直接子類化 a Node。
這樣你就可以
選項 1:創建append接受Node,例如:
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
}
所以現在你可以
let x = DoublyLinkedList<Search>()
let y = TransactionFilterNode(...)
x.append(newNode: y) // No problem
選項 2:子類Search而不是子類Node
即也許不是class TransactionFilterNode: Node<Search>您的意思class TransactionFilter: Search?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/497689.html
標籤:迅速
