title: Generics in Swift - "Generic parameter 'T' could not be inferred
body: <p>I'd like to return a <code>UIViewController</code> conforming to <code>MyProtocol</code> from a method, so I'm using the method signature:</p>
  
  <pre><code>func myMethod&lt;T where T : UIViewController, T : MyProtocol&gt;() -&gt; T {
  </code></pre>
  
  <p>First thing I don't understand: if <code>myMethod</code> returns e.g. a <code>MyViewController</code> which has to following signature, I have to force cast it:</p>
  
  <pre><code>class MyViewController: UIViewController, MyProtocol
  </code></pre>
  
  <p>I cannot simply <code>return MyViewController()</code> but I need to cast it like this: <code>return MyViewController() as! T</code> - why is this necessary?</p>
  
  <p>And the second thing: how can I use this method somewhere? I cannot simply say</p>
  
  <pre><code>let x = myMethod() as? UIViewController
  </code></pre>
  
  <p>as I get the error</p>
  
  <pre><code>Generic parameter 'T' could not be inferred
  </code></pre>
  
  <p>How can I achieve something like this? If I cast it to <code>MyViewController</code> it works, but I would like to avoid that of course.</p>
  
  <p><strong>EDIT: Example</strong></p>
  
  <pre><code>class MyViewController : UIViewController, MyProtocol {
  }
  
  protocol MyProtocol {
  }
  
  func myMethod&lt;T&gt;() -&gt; T where T : UIViewController, T : MyProtocol {
      return MyViewController() as! T // why is the cast necessary?
  }
  </code></pre>
  
  <p>ok, I do get one part, but why is the cast to <code>T</code> necessary? <code>MyViewController</code> is a subclass of <code>UIViewController</code> and conforms to the protocol, so no cast should be necessary, right?</p>