0

How do I add an extension method to a generic typed class, and access the generic type defined on the class to make the method typesafe?

The following method gives a compile error because T is not the same generic type defined on the class.

extension Array {
   mutating public func addTwo<T>(object: T) {
      append(object)
      append(object)
   }
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • possible duplicate of [How can I extend typed Arrays in Swift?](http://stackoverflow.com/questions/24027116/how-can-i-extend-typed-arrays-in-swift) – jtbandes Aug 10 '14 at 22:38

2 Answers2

3

Simply remove the <T>. You can reference T, or equivalently Element, inside the extension scope without it.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Why is it T? Is it because they used the key T as the generic type? If they used K instead I would have used K? So basically I need to see the source code in order to see what the generic type is referred to as? – aryaxt Aug 10 '14 at 22:40
  • Is it possible to accept an argument of type T which is also Equatable? – aryaxt Aug 10 '14 at 22:43
  • For that reason you may prefer to use `Element` which is a typealias in the generic definition. Your other question is [this one](http://stackoverflow.com/questions/24047164/extension-of-constructed-generic-type-in-swift). – jtbandes Aug 10 '14 at 22:46
0

The definition for Array uses T as a type parameter; thus, you have access to it in any extensions you might add to Array. In your case, the following works:

$ swift
Welcome to Swift!  Type :help for assistance.
  1> extension Array { 
  2.     mutating public func addTwo (obj: T) { append(obj); append(obj) } 
  3. }    
  4> class Foo {}
  5> var ar:[Foo] = []
ar: [Foo] = 0 values
  6> ar.addTwo(Foo())
  7> ar
$R0: [Foo] = 2 values {
  [0] = {}
  [1] = {}
}

Note that because the definition of Array has typealias Element = T you can use Element too (for readability).

GoZoner
  • 67,920
  • 20
  • 95
  • 145