2017-07-17 121 views
2

說我有下面的函數定義:帶完成處理程序的函數,何時執行完成?

func validResponse(data: Data?, response: URLResponse?, error: Error?, viewController: UIViewController, context: String?, withCompletion completion: @escaping (Bool?, String?) ->()) { 

那麼這個功能我裏面:

case 500: //internal server error 
    debug.log(tag: "NetworkHelper", content: "\(response!.url!.path) returned 500. Payload: \(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!)") 

    completion(true, "500, internal server error") 

    print("do something") 

print("do something")得到執行?我不想要它,但想知道在所有完成呼叫後我是否應該包括return

編輯:說我有這樣一串代碼:

if data == nil { 
    debug.log(tag: "NetworkHelper", content: "Error, did not receive any data on \(response!.url!.path)") 
    completion(false, "No data was received from the server") 
} 

if error != nil { 
    debug.log(tag: "NetworkHelper", content: "Error, calling GET on \(response!.url!.path)") 
    debug.log(tag: "NetworkHelper", content: error!.localizedDescription) 
    completion(false, genericError) 
} 

我需要調用每個completion通話後的回報?

+0

是的,它會被執行。最好刪除它,而不是留下無法訪問的代碼 –

+0

@CodeDifferent請參閱編輯。所以我需要在每個「完成」調用後包含'return'? – toast

+0

是的,因爲你不想執行後面的代碼。 'guard'是一個更加Swifty的解決方案,因爲它會迫使你從完成塊返回 –

回答

0

完成只是功能。如果你想在調用這個函數後執行一些東西,你可以在完成調用後添加這段代碼。如果你不想在完成後調用任何代碼,就不要寫這個代碼。

而且你應該使用檢查零的情況下後衛

guard let data = data else { return } 
debug.log(tag: "NetworkHelper", content: "Error, did not receive any data on \(response!.url!.path)") 
     completion(false, "No data was received from the server") 
相關問題