2

I'm trying to extend Array<T> in Swift to add a function that calls self.append. The problem is that Swift won't seem to let me do that - when I try the following code:

extension Array {
    mutating func AppendObj<T>(obj: T) {
        //...
        self.append(obj);
    }
}

it says 'T' is not convertable to 'T,' which I assume means that the 'T' the underlying Array is using might be different than the T passed to AppendObj. It also won't allow me to use extension Array<T> ("use of undeclared type T").

Is it possible to extend & use generic structs/methods in Swift? Thanks!

MatthewSot
  • 3,516
  • 5
  • 39
  • 58
  • If I may make a suggestion, don't call your method `AppendObj`. Instead, call it `appendObj`. Method names should begin with a lower case letter in Swift (and Obj-C). – Gregory Higley Dec 21 '14 at 20:05

1 Answers1

2

You shouldn't specify generics for the function, it overrides the existing template. Just leave it out:

extension Array {
    mutating func AppendObj(obj: T) {
        //...
        self.append(obj);
    }
}
drewag
  • 93,393
  • 28
  • 139
  • 128