OGeek|极客世界-中国程序员成长平台

标题: ios - 带有完成处理程序的函数,执行何时完成? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:18
标题: ios - 带有完成处理程序的函数,执行何时完成?

假设我有以下函数定义:

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 调用后调用 return?



Best Answer-推荐答案


完成只是功能。如果你想在调用这个函数之后执行一些东西,你只需在完成调用之后添加这个代码。如果你不想在完成后调用任何代码,就不要写这段代码。

你应该使用 guard 来检查 nil 大小写:

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

关于ios - 带有完成处理程序的函数,执行何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45141136/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4