title: Swift: Self type, subclassing and overriding methods
body: <p>The following code shows an Class A which is the superclass of class B. The function has the return type 'Self'. The overridden method in class B courses an error (see the comment).</p>
  
  <pre><code>class A {
      class func doSomething(param1: String) -&gt; Self {
          var entity = self()
  
          // Some code goes here...
  
          return entity
      }
  }
  
  class B: A {
      override class func doSomething(param1: String) -&gt; Self {
          var entity = super.doSomething(param1) as! B
  
          // Some code goes here...
  
          return entity // Error:'B' is not convertible to 'Self'
      }
  }
  </code></pre>
  
  <p>If I would have used instanceType in Objective-C it would work. So how can I get that working? Or is that not possible? </p>
  
  <p>I want to have the method the return type of the current overriding class.
  A workaround would be to have an init-method which accepts the superclass type as parameter.</p>
  
  <hr>
  
  <p>That brings up another question: an object casted to the current class isn't equal to self()?</p>
  
  <p>So what is the difference between</p>
  
  <pre><code>var entity = someObject as! B
  </code></pre>
  
  <p>and</p>
  
  <pre><code>var entity = self() // Current class / file is B
  </code></pre>
  
  <hr>
  
  <h2>EDIT:</h2>
  
  <pre><code>class func objectCast&lt;T: A&gt;(obj: A) -&gt; T {
      return obj as! T
  }
  </code></pre>
  
  <p>Returning objectCast(entity) instead of entity works.</p>
  
  <pre><code>class A {
      class func doSomething(param1: String) -&gt; Self {
          var entity = self()
  
          // Some code goes here...
  
          return entity
      }
  }
  
  class B: A {
      override class func doSomething(param1: String) -&gt; Self {
          var entity = super.doSomething(param1) as! B
  
          // Some code goes here...
  
          return objectCast(entity) // No error.
      }
  }
  </code></pre>
  
  <p>So… Why does it need that trick, it seems like I've a problem with understanding the meaning of 'Self'. Can anyone answer the second part of my question about the difference?</p>