title: How to use a protocol with associative type as return value in Swift?
body: <p>I'm trying to use a protocol with associated type as return value of a class func.</p>
  
  <p><a href="https://stackoverflow.com/questions/24708890/why-can-this-protocol-only-be-used-as-a-generic-constraint">Another post</a> here on stackoverflow is about the same question and based on this post's answer I tried the following:</p>
  
  <pre><code>// addArg takes a single Int argument and returns something, 
  // which is capable of adding a another Int argument
  class OpWithNoArg {
      func addArg&lt;OP: OpWithOneArg where OP.ArgType == Int&gt;(arg: Int) -&gt; OP {
          return OpWithOneArgImpl() // (1) error here !
      }
  }
  
  // a protocol with associated type, which allows adding another
  // argument of a not yet specified type
  protocol OpWithOneArg {
      typealias ArgType
      func addAnotherArg(arg: ArgType)
  }
  
  // an implementation of the protocol above, 
  // which fixes the associated type to an Int
  class OpWithOneArgImpl : OpWithOneArg {
      typealias ArgType = Int
      func addAnotherArg(arg: Int) {
          // ...
      }
  }
  </code></pre>
  
  <p>The error in Xcode 7.0 Beta 4 on line marked with (1) is</p>
  
  <blockquote>
    <p>cannot convert return expression of type 'OpWithOneArgImpl' to
    expected return type 'OP'</p>
  </blockquote>
  
  <p>If I change the return value to an optional and <code>nil</code> is returned, the sample compiles successfully:</p>
  
  <pre><code>// return null  
  class OpWithNoArg {
      func addArg&lt;OP: OpWithOneArg where OP.ArgType == Int&gt;(arg: Int) -&gt; OP? {
          // return OpWithOneArgImpl()
          return nil
      }
  }
  </code></pre>
  
  <p>Is this way of using a protocol with associative type as return value possible in swift, and if that's the case, how can the compiler error mentioned above be fixed? </p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>In Java, the code would be something like the following snippet. I try to find a way in Swift to achieve the same.</p>
  
  <pre><code>class C {
      &lt;T&gt; P&lt;T&gt; f(T arg) {
          return new PImpl();
      }
  }
  
  interface P&lt;S&gt; {
      void g(S arg);
  }
  
  class PImpl&lt;S&gt; implements P&lt;S&gt; {
      PImpl() {}
      public void g(S arg) {}
  }
  </code></pre>