无法通过完成处理程序将类型'()'的值转换为预期的参数类型'()->无效'

问题描述 投票:1回答:2

我正在尝试创建一个可以执行功能的完成块,但我不断收到错误:

无法将类型'()'的值转换为预期的参数类型'()->无效'

这里是功能:

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
ios swift completionhandler completion-block
2个回答
0
投票

您需要指定在多个完成情况下将发生的情况:

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()
          }

   }

0
投票

您的问题定义了一个名为removeAllLabels的函数,但随后您说当您调用removeAllCampusLabels时出现错误,而该问题并未定义。如果您检查在问题中输入的代码是否足以重现您要询问的错误,则将获得更好的帮助。

我假设您的函数实际上命名为removeAllLabels

这是您的removeAllLabels声明:

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

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

[我想,这是您尝试呼叫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() })
© www.soinside.com 2019 - 2024. All rights reserved.