title: superclass methods to return subclass type in swift
body: <p>I have this code:</p>
  
  <pre><code>class Dark: NSObject {
    class var className: String {
      return NSStringFromClass(self)!.componentsSeparatedByString(".").last!
    }
  
    var success = 0
  
    class func devour&lt;T: Dark&gt;(params: Int) -&gt; T {
      var s = T()
      return assign(s, params: params)
    }
  
    class func assign&lt;T: Dark&gt;(item: T, params: Int) -&gt; T{
      if item.dynamicType === self {
        item.success = params
      }
      return item
    }
  }
  
  class Black: Dark {
  }
  
  class Violet: Dark {
  }
  
  Black.className // returns "Black"
  Violet.className // returns "Violet"
  </code></pre>
  
  <p>The problem occurs when I do this:</p>
  
  <pre><code>var ret = Black.devour(5)
  ret.success //returns 0 which I expect to be 5
  
  ret.self // returns {Dark success 0} which I expect to be {Black success 0}
  </code></pre>
  
  <p>The problem here is that when the subclass uses the inherited method devour, it returns an object of type <code>Dark</code>. I want to be able to return the subclass type and not the superclass type when calling devour. Example when I do:</p>
  
  <pre><code>var ret = Black.devour(5)
  </code></pre>
  
  <p>The class of ret should be of class <code>Black</code> and not of class <code>Dark</code>.</p>
  
  <p>I hope someone can help me on this. Im really out of ideas. Thanks!
  I want to avoid chaining and I consider it last resort.</p>