title: How to check whether an object is kind of a dynamic class type in swift?
body: <p>I am implementing a function called <code>ofType</code> which filters out all the elements of the given type.</p>
  
  <p>Here are my codes:</p>
  
  <pre><code>class Animal {}
  class Mammal: Animal {}
  class Monkey: Mammal {}
  class Pig: Mammal {}
  class Human: Mammal {}
  
  extension Array {
      func ofType&lt;T&gt;(_ metatype: T.Type) -&gt; [T] {
          return flatMap { type(of: $0) == metatype ? $0 as? T : nil }
  //      return flatMap { $0 as? T } // This is not working as the T is always the static type of the parameter, which is Animal in this example.
  //      return flatMap { $0 as? metatype } // This is not working either because of the grammar restriction.
      }
  }
  
  let animals = [Monkey(), Pig(), Human(), Mammal(), Animal()]
  func animalType() -&gt; Animal.Type {
      return Mammal.self
  }
  animals.ofType(animalType()).count // returns 1, expect to be 4.
  </code></pre>
  
  <p>In Objc, I can use <code>isKindOf()</code> to check whether an object is an instance of the class or the subclass. There are similar operations in swift <code>is</code> and <code>as</code>, but the type after them should be a static type, not a dynamic type value (e.g. I can write <code>is Mammal</code>, but not <code>is Mammal.self</code>).</p>
  
  <p>I cannot use the type parameter <code>T</code> either because, in this example, the <code>T</code> equals to <code>Animal</code>, which is not what I want.</p>
  
  <p>Do you have any idea about how to implement this function?</p>