title: Returning a subclass from its base class in swift
body: <p>I am trying to allow a method in a super class to return an instance of the subclass so that I can use method chaining with methods across both the parent and the child.</p>
  
  <p>However, I am getting the error "BaseClass does not have a member named someOtherChainableMethod" when I attempt to chain the methods. Here is my code:</p>
  
  <pre><code>class BaseClass {
      func someChainableMethod() -&gt; BaseClass {
          return self
      }
  }
  
  class ChildClass: BaseClass {
      func someOtherChainableMethod() -&gt; ChildClass {
          return self
      }
  }
  
  let childClass = ChildClass
  
  childClass.someChainableMethod().someOtherChainableMethoid()
  </code></pre>
  
  <p>The issue seems to be that the 'return self' in the parent chain-able method is returning an instance with type <code>BaseClass</code> rather than <code>ChildClass</code>.</p>
  
  <p>I have also tried this with generics and failed, this is what I tried:</p>
  
  <pre><code>class BaseClass&lt;T&gt; {
      func someChainableMethod() -&gt; T {
          return self
      }
  }
  
  class ChildClass: BaseClass&lt;ChildClass&gt; {
      func someOtherChainableMethod() -&gt; ChildClass {
          return self
      }
  }
  
  let childClass = ChildClass
  
  childClass.someChainableMethod().someOtherChainableMethoid()
  </code></pre>
  
  <p>In this case the error from the <code>BaseClass</code> <code>someChainableMethod</code> method, is "BaseClass is not convertible to T".</p>