2016-07-26 47 views
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 { 
... 
} 

到目前为止,我了解的最后一个函数意味着该类型声明要求泛型类型T随后其在completionHandler使用的协议ResponseJSONObjectSerializable,这需要Response结构具有类型声明<Value, NSError> -> Void,然后返回self精神上解析FUNC声明与仿制药和完成处理

我觉得我可能会喜欢,除了最后的self部分。

+0

看看这个答案http ://stackoverflow.com/a/33200294/1422333 –

回答

0

对于前两个声明你是对的。

最后一个有点奇怪,因为Alamofire如何做响应串行器。你可以将多个串行这样的:

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

当该代码被调用,这是发生了什么:

  • Alamofire.request(myRequest)创建请求和处理
  • .responseString & .responseArray队列中得到他们的响应序列化添加到队列
  • 网络调用发生
  • 当我t完成(无论是失败还是成功),队列调用所有添加到它的响应序列化器(即,.responseString & .responseArray
  • 当每个序列化器运行时,它的完成处理器可用于“返回”结果给调用者(这是因为它的异步它不能直接做)

此代码将不会(几乎)同样的事情:

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() 

但​​意味着网络电话没有得到开始直到alamofireRequest.resume()是calle d。它默认为true,所以所有的响应串行器必须作为与manager.request(myRequest)相同的语句的一部分来添加。

因为响应串行回归自我,我们可以缩短这个:

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

要这样:

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

如果我们使用manager.startsRequestImmediately = true那么我们就需要对请求的局部变量根本没有(因为我们不必拨打alamofireRequest.resume()):

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