具有完成处理程序的函数,何时执行完成?

时间:2017-07-17 09:56:51

标签: ios swift

说我有以下功能定义:

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来电后,我是否需要致电回复?

1 个答案:

答案 0 :(得分:0)

完成只是功能。如果要在调用此函数后执行某些操作,则只需在完成调用后添加此代码。如果您不想在完成后调用任何代码,请不要编写此代码。

你应该使用 guard 来检查nil case:

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