假设我有一个具有完成处理程序的函数,然后调用另一个函数,使用这样的完成处理程序:
func register(withCompletion complete: @escaping (() -> Void)) { self.sendRegisterRequest(withCompletion: { (error: Error?) -> () in if error != nil { self.performSegue(withIdentifier: "ErrorVCSegue", sender: nil) } else { complete() } }) }如果发生错误,它将通过调用complete()消除。
我可以这样离开,不用调用complete()吗? 我不需要从这个函数返回,因为我现在想要转到另一个View Controller。
谢谢。
Say I have a function that has a completion handler, then calls another function, with a completion handler like this:
func register(withCompletion complete: @escaping (() -> Void)) { self.sendRegisterRequest(withCompletion: { (error: Error?) -> () in if error != nil { self.performSegue(withIdentifier: "ErrorVCSegue", sender: nil) } else { complete() } }) }In the event of an error, it will segue away with calling complete().
Am I ok to segue away like this, without calling complete()? I do not need to return from this function as I'm now wanting to go to another View Controller.
Thanks.
最满意答案
这是一个坏主意。 无论如何都应该调用完成处理程序。 呼叫者正在等待回复。 它想知道什么时候完成。 这就是拥有完成处理程序的重点。
在你的情况下(像许多其他情况一样),如果完成处理程序接受布尔参数(和/或错误参数)会更好。 这样,完成处理程序提供了有关方法成功或失败的一些基本信息。
This is a bad idea. A completion handler should be called no matter what. The caller is waiting for a response. It wants to know when it is done. That's the whole point of having a completion handler.
In your case (like many other cases), it would be much better if the completion handler accepted a boolean parameter (and/or an error parameter). This way the completion handler provides some basic information about the success or failure of the method.
更多推荐
发布评论