How to extend Array for generic type?

╄→гoц情女王★ 提交于 2019-12-10 10:59:12

问题


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:

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.

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

    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:


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
    }
}


来源:https://stackoverflow.com/questions/46626775/how-to-extend-array-for-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!