title: Using Swift Generics to Call a Non-Generic Library
body: <p>I'm trying to write a generic Swift wrapper for some of the vector operations in the Accelerate vDSP framework and I'm running into a problem calling the functions in a generic way.</p>
  <p>My vector struct looks like:</p>
  <pre><code>public struct Vector&lt;T&gt; {
    let array: [T]
    public static func add(_ a: [T], _ b: [T]) -&gt; [T] {
      vDSP.add(a, b)
    }
  
    public static func + (_ lhs: Self , _ rhs: Self) -&gt; Self {
      Self.add(lhs.array, rhs.array)
    }
  }
  </code></pre>
  <p>The problem is the <code>add</code> function is overloaded to either take Floats and return Floats or take Doubles and return Doubles. Since the type isn't known at compile time I get an error <code>No exact matches in call to static method 'add'</code></p>
  <p>The only way I've found to get around this is to explicitly check the type before the call and cast:</p>
  <pre><code>public static func add(_ a: [T], _ b: [T]) -&gt; [T] {
    if T.self is Float.Type {
      return vDSP.add(a as! [Float], b as! [Float]) as! [T]
    } else {
      return vDSP.add(a as! [Double], b as! [Double]) as! [T]
    }
  }
  </code></pre>
  <p>or to use constrained methods</p>
  <pre><code>public static func add(_ a: T, _ b: [T]) -&gt; [T] where T == Float { vDSP.add(a, b) }
  public static func add(_ a: T, _ b: [T]) -&gt; [T] where T == Double { vDSP.add(a, b) }
  </code></pre>
  <p>Both of these lead to uncomfortable code duplication, and what's more if I had more than two types (for example if supported is added for the upcoming Float16 type) I'd need to keep adding more and more cases. The latter approach seems especially bad since the method bodies are identical.</p>
  <p>I'd like to be able to do something like <code>vDSP.add&lt;T&gt;(a, b)</code> but it seems Swift doesn't support this. Is there some other way to acheive this and avoid the code duplication?</p>