【问题标题】:How exactly does this completion handler work?这个完成处理程序究竟是如何工作的?
【发布时间】:2021-06-18 17:48:45
【问题描述】:

我对闭包、接收参数的闭包、尾随闭包和完成处理程序进行了一些研究,但我很难理解何时传递完成的两个参数、管理器和文件。在 pick() 函数定义中,函数范围内没有任何地方使用 completion(manager, file) 语法调用完成。但是,有一个 present 方法,我认为我遗漏了有关 present() 的一些内容,其中可能包括对带有适当参数的完成闭包的调用。非常感谢您的帮助。

public func pick(from vc: UIViewController?, withCompletion completion: @escaping (_ manager: HSDriveManager?, _ file: GTLRDrive_File?) -> Void) {
        viewer?.completion = completion
        viewer?.shouldSignInOnAppear = true
        
        //As of now, present() seems to include the calling of the completion closure.
        //self is the HSDriverPicker class
        print(type(of: self))
        vc?.present(self, animated: true)
        
    }

下面的代码是pick的函数调用。让我感到困惑的是,为了让 manager 和 file 在函数调用中的某处像完成闭包的参数一样起作用,有一部分会传递这些参数。我没有看到他们。我希望您能深入了解当前方法的具体作用以及它是否会使用必要的参数调用闭包。

picker.pick(from: self) {
                (manager, file) in

                print("picked file: \(file?.name ?? "-none-")")

                let destinationPath = "/Users/james/Desktop/tests"
                
                manager!.downloadFile(file!, toPath: destinationPath, withCompletionHandler: {
                    error in

                    if error != nil {
                        print("Error downloading : \(error?.localizedDescription ?? "")")
                    }
                    else {
                        print("Success downloading to : \(destinationPath)")
                    }
                })
            }

【问题讨论】:

  • 看到viewer?.completion = completion这一行了吗?这表明pick 不负责调用完成处理程序。 viewer(不管是什么)
  • @Sweeper 非常感谢。我会检查属于查看器的代码。
  • 与您的问题无关,但在 Swift 3 中已放弃带有下划线字符和参数标签的闭包语法。这就足够了:@escaping (HSDriveManager?, GTLRDrive_File?) -> Void

标签: swift closures swift5 completionhandler


【解决方案1】:

函数present(_:animated:) 不负责调用完成闭包。 viewer?.completion = completion 意味着 viewer 将负责在其范围内调用完成闭包(这就是使用 @escaping 的原因,即闭包将比您传递给它的范围更长)。 managerfile 这两个参数不应该由客户端传递,而是公开给客户端,以便调用 picker.pick 的任何人都可以使用这些属性并执行随后将在 @987654328 内部调用的特定操作@。带参数的闭包仅仅意味着客户端可以使用该参数,而不必担心这些参数将被传递给谁以及何时传递。

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多