在 swift 中使用带参数的预定义函数作为完成块

Using predefined function with parameters as completion block in swift

编辑:我认为问题是 Swift 语法,但问题是我不知道 UIViewController.presentViewController 指定了不带输入参数的完成处理程序的签名。

我必须为 presentViewController 提供完成处理程序。我想提供的完成处理程序接受一个输入参数。在 swift 中处理此问题的语法是什么?

如果处理程序没有接受输入参数,它将如下所示:

self.presentViewController(activityVC, animated: true, completion: myHandler)

但是如果 myHandler 是这样声明的,上面的行会是什么样子:

func myHandler(myParameter: AnyObject){
    ...
}

我相信您希望执行以下操作:

function myHandler(myParameter: (() -> Void)) {
//code here
}

当然 -> Void 会根据您是否需要该功能而改变

不幸的是,这不起作用。您不能只传入一个对完成块具有无效类型的函数。它期望一个没有任何参数且没有 return 类型/void 的闭包。您正在提供一个需要 AnyObject 和 return nothing / void 的函数。因此,预期的 (() -> Void) 与提供的 ((AnyObject) -> Void)

之间存在不匹配

程序如何知道将什么作为 myParameter 传递给 myHandler

我能想到的唯一方法是为自定义完成处理程序编写一个包装器:

self.presentViewController(activityVC, animated: true, completion:{self.myHandler("")})

这样你提供了一个调用 myHandler 的完成块,但实际上为 myParameter.

提供了一个值

我应该在问这个问题之前先看看 declaration of presentViewController,但我对闭包没有经验,认为任何闭包都可以通过。事实证明,问题在于 presentViewController 采用了非常具体的

形式的闭包
(() -> Void)?

完整签名在这里:

func presentViewController(_ viewControllerToPresent: UIViewController,
              animated flag: Bool,
            completion completion: (() -> Void)?)

所以答案是 presentViewController 不能采用本身采用另一个参数的完成处理程序。