繁体   English   中英

无法使用完成处理程序将类型“()”的值转换为预期的参数类型“()-> Void”

[英]Cannot convert value of type '()' to expected argument type '() -> Void' with a completionHandler

我正在尝试创建一个完成块,可以在其中执行 function 但我不断收到错误消息:

无法将类型“()”的值转换为预期的参数类型“()-> Void”

这是 function:

var labelViews : [LabelViews] = []

private func removeAllLabels(completion: (() -> Void)) {
    guard let mapController = viewModel.mapController,
        let currentMap = mapController.currentMap else {
            return
    }

    LabelViews.forEach { view in
        DispatchQueue.main.async {
            mapController.removeComponent(view, on: currentMap)
        }  
    }
    completion()
}

但是当我尝试使用它时,我得到了错误:

self.removeAllCampusLabels(completion: self.labelViews.removeAll()) // error happens here

您需要指定在多个完成情况下会发生什么:

var labelViews : [LabelViews] = []



  private func removeAllLabels(completion: nil) {
                guard let mapController = viewModel.mapController,
                    let currentMap = mapController.currentMap else {
                        return
                }

                LabelViews.forEach { view in
                    DispatchQueue.main.async {
                        mapController.removeComponent(view, on: currentMap)}  
    }
                func comp(completion: () -> Void) {
                print("Success")
                completion()
          }

   }

假设removeAllLabelsremoveAllCampusLabels是相同的方法(忽略错字),替换方法调用

self.removeAllCampusLabels(completion: self.labelViews.removeAll())

self.removeAllCampusLabels { self.labelViews.removeAll() }

您的问题定义了一个名为removeAllLabels的 function ,但是您说当您调用removeAllCampusLabels时发生错误,您的问题没有定义。 如果您检查您在问题中输入的代码是否足以重现您所询问的错误,您将获得更好的帮助。

我假设您的 function 实际上名为removeAllLabels

这是您的removeAllLabels声明:

private func removeAllLabels(completion: (() -> Void))

这是一个带有一个参数的 function,称为completion 该参数必须具有类型() -> Void ,这意味着参数本身必须是 function ,它不接受 arguments 并且不返回任何内容。

以下是(我假设)您尝试调用removeAllLabels的方式:

self.removeAllLabels(completion: self.labelViews.removeAll())

让我们分解一下:

let arg = self.labelViews.removeAll()
self. removeAllLabels(completion: arg)

arg的类型是什么? 我们需要它是() -> Void 但是如果我们在 Xcode 中单击它,我们会看到arg的类型为() (与Void相同)。 事实上,Swift 会发出警告:

推断常量 'arg' 具有类型 '()',这可能是意料之外的

您可能想要做的是将removeAll调用包装在一个闭包中,如下所示:

let arg = { self.labelViews.removeAll() }
self.removeAllLabels(completion: arg)

一旦你消除了错误,你可以将它重新组合在一个语句中:

self.removeAllLabels(completion: { self.labelViews.removeAll() })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM