0
public protocol ResponseJSONObjectSerializable {
  init?(json: SwiftyJSON.JSON)
}

public struct Response<Value, Error: ErrorType> {
...
}

public func responseArray<T: ResponseJSONObjectSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
...
}

So far I understand the last function to mean that the type declaration requires generic type T which follows the protocol ResponseJSONObjectSerializable which is used in a completionHandler which takes a Response struct which has a type declaration of <Value, NSError> -> Void and then returns a self?

I feel like I might grok all of it except the last self part.

Idr
  • 6,000
  • 6
  • 34
  • 49

1 Answers1

0

You're right about the first two declarations.

The last one is a bit odd because of how Alamofire does response serializers. You can chain multiple serializers like this:

Alamofire.request(myRequest)
  .responseString { // handle response as string }
  .responseArray { // handle response as array }

When that code gets called this is what happens:

  • Alamofire.request(myRequest) creates the request and a queue for handlers
  • .responseString & .responseArray get their response serializers added to the queue
  • The network call happens
  • When it's done (whether it fails or succeeds), the queue calls all of the response serializers that were added to it (i.e., .responseString & .responseArray)
  • When each serializer gets run, it's completion handler can be used to "return" results to the caller (which it can't do directly because it's async)

This code would does (almost) the same thing:

let manager = Alamofire.Manager.sharedInstance
manager.startsRequestImmediately = false
let alamofireRequest = manager.request(myRequest)
alamofireRequest.responseString { // handle response as string }
alamofireRequest.responseArray { // handle response as array }
alamofireRequest.resume()

But manager.startsRequestImmediately = false means that the network call doesn't get started until alamofireRequest.resume() is called. It's true by default so all of the response serializers have to be added as part of the same statement as manager.request(myRequest).

Since the response serializers return self, we can shorten this:

let alamofireRequest = manager.request(myRequest)
alamofireRequest.responseString { // handle response as string }
alamofireRequest.responseArray { // handle response as array }

To this:

let alamofireRequest = manager.request(myRequest)
  .responseString { // handle response as string }
  .responseArray { // handle response as array }

And if we use manager.startsRequestImmediately = true then we don't need the local var for the request at all (since we don't have to call alamofireRequest.resume()):

manager.request(myRequest)
  .responseString { // handle response as string }
  .responseArray { // handle response as array }
Christina
  • 795
  • 7
  • 9