带完成处理程序的函数,何时执行完成?
问题描述:
说我有下面的函数定义:带完成处理程序的函数,何时执行完成?
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
通话后的回报?
答
完成只是功能。如果你想在调用这个函数后执行一些东西,你可以在完成调用后添加这段代码。如果你不想在完成后调用任何代码,就不要写这个代码。
而且你应该使用检查零的情况下后卫:
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")
是的,它会被执行。最好删除它,而不是留下无法访问的代码 –
@CodeDifferent请参阅编辑。所以我需要在每个“完成”调用后包含'return'? – toast
是的,因为你不想执行后面的代码。 'guard'是一个更加Swifty的解决方案,因为它会迫使你从完成块返回 –