我写了这些简单的泛型类,效果很好:

class LinkedListNode <T> {
    var value: T
    var next: LinkedListNode<T>?
    weak var prev: LinkedListNode<T>?
    init(value: T) {
        self.value = value
        self.next = nil
    }
}

class LinkedList<T> {
    var first: LinkedListNode<T>? = nil
    var last: LinkedListNode<T>? = nil
    var count = 0
    @discardableResult func append(_ value: T) -> LinkedListNode<T> {
        let new = LinkedListNode(value: value)
        new.prev = last
        last?.next = new
        count += 1
        last = new
        if first == nil {
            first = new
        }
        return new
    }
}

我用它来形容:
let list = LinkedList<Int>()
list.append(3)
let lastNode = list.append(5)

现在我意识到有些情况下我需要一个定制的节点:CustomNode<T>LinkedListNode<T>的子类。因此,我希望能够将要用作节点的类传递为:
let list = LinkedList<CustomNode<Int>>()
list.append(3)
let customNode = list.append(5)

我怎样才能声明我的班级有这样或类似的东西?
我试过下面的声明,但出现了奇怪的错误。这可能吗?
class LinkedList<Node<T>: LinkedListNode<T>> { ...

更新2019/07/26。
即使使用kamran的方法,这个方法也不会编译。我不确定没有协议这是否可行。看我对卡姆兰回答的评论。
func remove(node: LinkedListNode<T>) { // change to `func remove(node: U)`
    node.next?.prev = node.prev
    node.prev?.next = node.next
    if node === first {
        first = first?.next
    }
    if node === last {
        last = last?.prev // Error here: "Cannot assign value of LinkedListNode<T>? to U?"
    }
}

最佳答案

您正在尝试的语法可以实现如下:

class LinkedListNode <T> {
    var value: T
    var next: LinkedListNode<T>?
    weak var prev: LinkedListNode<T>?
    required init(value: T) {
        self.value = value
        self.next = nil
    }
}

class GenericCustomNode<T>: LinkedListNode<T> {

    required init(value: T) {
        super.init(value: value)
    }
}

class NonGenericCustomNode: LinkedListNode<Int> {

    required init(value: Int) {
        super.init(value: value)
    }
}

class LinkedList<T, U: LinkedListNode<T>> {
    var first: U? = nil
    var last: U? = nil
    var count = 0
    @discardableResult func append(_ value: T) -> U {
        let new = U(value: value)
        new.prev = last
        last?.next = new
        count += 1
        last = new
        if first == nil {
            first = new
        }
        return new
    }

    func remove(node: U) {
        node.next?.prev = node.prev
        node.prev?.next = node.next
        if node === first {
            first = first?.next as? U
        }
        if node === last {
            last = last?.prev as? U
        }
    }
}

用法:
let list = LinkedList<Int, LinkedListNode<Int>>()
list.append(5)
print(list.first?.value)

let someCustom = LinkedList<Int, GenericCustomNode<Int>>()
someCustom.append(15)

print(someCustom.first?.value)

let otherCustom = LinkedList<Int, NonGenericCustomNode>()
otherCustom.append(2)
print(otherCustom.first?.value)

输出:
 Optional(5)
 Optional(15)
 Optional(2)

关于swift - 在swift中以泛型类作为参数声明泛型类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57117876/

10-13 03:43