title: Creating a generic method with AlamoFire in Swift
body: <p>I am using AlamoFire for my API calls, and have something like this all over my project:</p>
  
  <pre><code>static func login(userName: String, password: String) -&gt; User {
      let parameters = ["userName": userName , "password": password]
      let user = User()
      Alamofire.request(.POST, "myserver.com/login", parameters: parameters, encoding: .JSON)
          .validate()
          .responseObject { (response: Response&lt;User, NSError&gt;) in
              switch response.result {
              case .Success(let value):
                  user.valueHandle?(value)
              case .Failure(let error):
                  user.errorHandle?(error)
              }
      }
  
      return user
  }
  </code></pre>
  
  <p>(see <a href="https://stackoverflow.com/a/37949671/406322">https://stackoverflow.com/a/37949671/406322</a> on how I came up with the above code).</p>
  
  <p>The problem is that I have a lot of objects other than User and there is code repetition with only the type of the object different, so I'm trying to create a generic method, something like this:</p>
  
  <pre><code>static func sendRequest&lt;T&gt;(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]?) -&gt; T {
          let response : T
          Alamofire.request(method, urlString, parameters:parameters)
              .validate()
              .responseObject { (response: Response&lt;T, NSError&gt;) in
                  switch response.result {
                  case .Success(let value):
                      response.valueHandle?(value)
                  case .Failure(let error):
                      response.errorHandle?(error)
                  }
          }
  
          return response 
   }
  </code></pre>
  
  <p>But Swift is complaining:</p>
  
  <pre><code>Cannot convert value of type '(Response&lt;T, NSError&gt;) -&gt; ()' to expected argument type 'Response&lt;_, NSError&gt; -&gt; Void'
  </code></pre>
  
  <p>This is so I can do something like this:</p>
  
  <pre><code>User.swift
  static func login(userName: String, password: String) -&gt; User {
          let parameters = ["userName": userName, "password": password]
      return sendRequest&lt;User&gt;(.GET, "http://myserver.com/users", parameters)
  }
  </code></pre>
  
  <p>and in my calling code:</p>
  
  <pre><code>User.login(txtUserName.text!, password: txtPassword.text!)
              .success { (value) in
                  var user = value as! User
                  //do something with user
              }
              .error { (error) in
                  //show error
              }
  </code></pre>
  
  <p>What am I not doing right?</p>