如何扩展泛型类型的数组?

时间:2022-03-21 22:35:16

I have a class for a linked list declared like this:

我有一个这样声明的链表的类:

 class LinkedNode<T> {

    let data: T
    var next: LinkedNode<T>?


    func traverseList(process: (LinkedNode<T>) -> ()) { ... }
}

What I want to do is extend Array to have an initialiser that converts my LinkedNode class to an array of linked nodes. I tried this:

我要做的是扩展数组,使其具有将LinkedNode类转换为链接节点数组的初始化器。我试着这样的:

extension Array where Element == LinkedNode<T> {

  init(node: LinkedNode<T>)
  {
      var result = [LinkedNode<T>]()
      traverseList { result.append($0) }
      return result
  }
}

But that gives errors that T is undeclared. I have tried taking it out and doing other things, but nothing has worked.

但这就产生了错误T是未声明的。我试着把它拿出来做其他的事情,但是没有成功。

I was able to get the same results with a method on the LinkedNode class:

我可以通过LinkedNode类上的一个方法得到相同的结果:

    func array() -> [LinkedNode<T>]
    {
        var result = [LinkedNode<T>]()
        traverseList { result.append($0) }
        return result
    }

But I would prefer an array initialiser since so many other collection types have that initialiser.

但是我更喜欢数组初始化器,因为很多其他集合类型都有这个初始化器。

1 个解决方案

#1


4  

You can declare a generic parameter in initializer definition.

可以在初始化器定义中声明泛型参数。

extension Array {

    init<T>(node: LinkedNode<T>)
        where Element == LinkedNode<T>
    {
        var result = [LinkedNode<T>]()
        node.traverseList { result.append($0) }
        self = result
    }
}

#1


4  

You can declare a generic parameter in initializer definition.

可以在初始化器定义中声明泛型参数。

extension Array {

    init<T>(node: LinkedNode<T>)
        where Element == LinkedNode<T>
    {
        var result = [LinkedNode<T>]()
        node.traverseList { result.append($0) }
        self = result
    }
}