2016-07-26 54 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 }