title: Generic completion handler in Swift
body: <p>I have a method which has a method named <code>performRequest()</code>. It takes a <code>JSONRequest</code> parameter. <code>JSONRequest</code> looks something like this:</p>
  
  <pre><code>public typealias JSONCompletionHandler = ([Entity]?, NSError?) -&gt; Void
  
  public class JSONRequest: Request {
      public var completionHandler: JSONCompletionHandler
      public var endPoint: String
  }
  </code></pre>
  
  <p>And <code>performRequest()</code> looks like this:</p>
  
  <pre><code>public func performJSONRequest&lt;T where T: Entity&gt;(jsonRequest: JSONRequest, _: Type) {
          // Make a request which returns a data object
          var entities = self.convertJSONData(data, jsonKey: jsonRequest.jsonKey, T.self)
          // Error: 'T' is not identical to 'Entity'
          jsonRequest.completionHandler(entities, error)
  }
  </code></pre>
  
  <p>As you can see, it calls <code>convertJSONData()</code> which looks like this:</p>
  
  <pre><code>func convertJSONData&lt;T where T: Entity&gt;(jsonData: AnyObject, _: T.Type) -&gt; [T] {
          // Convert the data into Swift collection classes, enumerate over them, and create model objects
          var json = JSON(data: jsonData as NSData, options: nil, error: nil)
          var entities = [T]()
  
          for obj in json {
              let book = T(json: obj)
              entities.append(book)
          }
  
      return entities
  </code></pre>
  
  <p>Entity is a protocol which all my model classes, for example <code>Author</code> and <code>Book</code>, conform to.</p>
  
  <p>It defines one method: <code>init(json: JSON)</code>. Since <code>T</code> is defined as <code>T:Entity</code>, I can just call <code>T:(json: obj)</code> to create instances of any class conforming to <code>Entity</code>.</p>
  
  <p>I want to be able to use <code>performJSONRequest()</code> to perform request for <em>any</em> object conforming to Entity. For example, I want to build a request for Book instances like this:</p>
  
  <pre><code>var request = JSONRequest(endPoint: "books") { (let object: [Entity]?, let error: NSError?) -&gt; Void in
      // Cast object to [Book] and have fun
  }
  
  performJSONRequest&lt;Book&gt;(request)
  </code></pre>
  
  <p>I can't for the life of me find out how I would implement this. Right now, I get an error in the <code>performJSONRequest()</code> method saying <code>'T' is not identical to 'Entity'</code>. If I define the array in the completion handler as <code>[AnyObject]</code> I get the same error: <code>'T' is not identical to 'AnyObject'</code>.</p>
  
  <p>Thanks for any help! </p>