title: Generic function taking a type name in Swift
body: <p>In C#, it's possible to call a generic method by specifying the type:</p>
  
  <pre><code>public T f&lt;T&gt;()
  {
     return something as T
  }
  
  var x = f&lt;string&gt;()
  </code></pre>
  
  <p>Swift doesn't allow you to specialize a generic method when calling it. The compiler wants to rely on type inference, so this is not possible:</p>
  
  <pre class="lang-swift prettyprint-override"><code>func f&lt;T&gt;() -&gt; T? {
      return something as T?
  }
  
  let x = f&lt;String&gt;() // not allowed in Swift
  </code></pre>
  
  <p>What I need is a way to pass a type to a function and that function returning an object of that type, using generics</p>
  
  <p>This works, but it's not a good fit for what I want to do:</p>
  
  <pre class="lang-swift prettyprint-override"><code>let x = f() as String?
  </code></pre>
  
  <p><strong>EDIT (CLARIFICATION)</strong></p>
  
  <p>I've probably not been very clear about what the question actually is, it's all about a simpler syntax for calling a function that returns a given type (any type). </p>
  
  <p>As a simple example, let's say you have an array of Any and you create a function that returns the first element of a given type:</p>
  
  <pre class="lang-swift prettyprint-override"><code>// returns the first element in the array of that type
  func findFirst&lt;T&gt;(array: [Any]) -&gt; T? {
      return array.filter() { $0 is T }.first as? T
  }
  </code></pre>
  
  <p>You can call this function like this:</p>
  
  <pre class="lang-swift prettyprint-override"><code>let array = [something,something,something,...]
  
  let x = findFirst(array) as String?
  </code></pre>
  
  <p>That's pretty simple, but what if the type returned is some protocol with a method and you want to call the method on the returned object:</p>
  
  <pre class="lang-swift prettyprint-override"><code>(findFirst(array) as MyProtocol?)?.SomeMethodInMyProtocol()
  (findFirst(array) as OtherProtocol?)?.SomeMethodInOtherProtocol()
  </code></pre>
  
  <p>That syntax is just awkward. In C# (which is just as strongly typed as Swift), you can do this:</p>
  
  <pre><code>findFirst&lt;MyProtocol&gt;(array).SomeMethodInMyProtocol();
  </code></pre>
  
  <p>Sadly, that's not possible in Swift.</p>
  
  <p>So the question is: <strong>is there a way to accomplish this with a cleaner (less awkward) syntax.</strong></p>