title: Generics call with Type T in Swift
body: <p>In my application I want to create an generic method which creates an array of object depening on the given type T.</p>
  
  <p>I created the following function:</p>
  
  <pre><code>func getArray&lt;T : ROJSONObject&gt;(key:String) -&gt; T[] {
      var elements = T[]()
  
      for jsonValue in getValue(key).array! {
          var element = T()
  
          element.jsonData = jsonValue
          elements.append(element)
      }
  
      return elements
  }
  </code></pre>
  
  <p>Now I want to pass the type when I call the method, so it does know which type it should create internally. I think in Java and C# you can use a method like that:</p>
  
  <pre><code>object.getArray&lt;Document&gt;("key")
  </code></pre>
  
  <p>When I call it like that, I always get the error:</p>
  
  <pre><code>Cannot explicitly specialize a generic function
  </code></pre>
  
  <p>So my fix was to define an additional parameter containing an instance of the type T so it does automatically detect the type:</p>
  
  <pre><code>func getArray&lt;T : ROJSONObject&gt;(key:String, type:T) -&gt; T[] {
      var elements = T[]()
  
      for jsonValue in getValue(key).array! {
          var element = T()
  
          element.jsonData = jsonValue
          elements.append(element)
      }
  
      return elements
  }
  </code></pre>
  
  <p>Is there really no other way to get that behaviour without passing an unused instance? Or am I misunterstanding something?</p>
  
  <p><strong>Further Testing</strong></p>
  
  <p>After the answer of jtbandes I did some more testing. I tried to force the Type by adding the <code>as</code> in the call.</p>
  
  <pre><code>class Person {
  
      init() { }
  
      func getWorkingHours() -&gt; Float {
          return 40.0
      }
  }
  
  class Boss : Person {
      override func getWorkingHours() -&gt; Float {
          println(100.0)
          return 100.0
      }
  }
  
  class Worker : Person {
      override func getWorkingHours() -&gt; Float {
          println(42.0)
          return 42.0
      }
  }
  
  func getWorkingHours&lt;T : Person&gt;() -&gt; T {
      var person = T()
      person.getWorkingHours()
  
      return person
  }
  
  var worker:Worker = getWorkingHours() as Worker
  var boss:Boss = getWorkingHours() as Boss
  worker.getWorkingHours() // prints out 40.0 instead of 42.0
  boss.getWorkingHours() // prints out 40.0 instead of 100.0
  </code></pre>
  
  <p>So somehow the type is always the base type even I've specified the type with the <code>as</code> keyword. I know the example does not make much sense, but it was just for testing purpose..</p>