Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Array for generic type?

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.

like image 856
MarkAurelius Avatar asked Aug 05 '26 14:08

MarkAurelius


1 Answers

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
    }
}
like image 144
OOPer Avatar answered Aug 08 '26 10:08

OOPer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!