title: Base class static method returns type of subclass in Swift
body: <p>I want to have a base class static method which returns an array of the subclass type. Here is my current implementation. It works, but I have a small problem with it.</p>
  
  <pre><code>class Animal {
      required init() { }
      public static func generateMocks&lt;T: Animal&gt;() -&gt; [T] {
          var mocks: [T] = []
          // some implementation goes here...
          for _ in 0..&lt;10 {
              mocks.append( T() )
          }
          //
          return mocks
      }
  }
  
  
  let myMockAnimals: [Animal] = Animal.generateMocks() // this gives me type [Animal]
  
  class Dog: Animal {
      // dog things
      var isCute = true
  }
  
  let myMockDogs: [Dog] = Dog.generateMocks() // this gives me type [Dog]
  print(myMockDogs.first?.isCute) // true
  
  /* My problem is that it is very annoying to have to declare my
     myMockDogs variable as type "[Dog]". I would like it to
     automatically infer this type. Like this: */
  
  let myMockDogs2 = Dog.generateMocks() // oh no! It gives me type [Animal]
  print(myMockDogs2.first?.isCute) // error! Value of type 'Animal' has no member 'isCute'
  if let dog = myMockDogs2.first! as Dog { // error! 'Animal' is not convertible to 'Dog';
      print(dog)
  }
  </code></pre>
  
  <p>So my generic static function <code>generateMocks</code> is able to return the correct subclass when I specify the type of object I am expecting, like <code>let myMockDogs2: [Dog] =...</code>, but when I drop the explicit type I am expecting like in <code>let myMockDogs2 =...</code> then it suddenly goes back to using <code>Animal</code> as the type used for the generic function resulting in an array <code>[Animal]</code>.</p>
  
  <p><strong>Is there a way to modify the <code>generateMocks</code> function which would cause <code>let myMockDogs2 = Dog.generateMocks()</code> to use type <code>Dog</code> for the generic <code>T</code> automatically?</strong></p>
  
  <p>You can copy this code into a Playground too! It works there! I'm really scared there's no solution to this, but maybe a Swift genius out there has an idea.</p>