【问题标题】:Cannot convert value of type '()' to expected argument type '(() -> Void)?' in swiftui无法将“()”类型的值转换为预期的参数类型“(() -> Void)?”在 swiftui
【发布时间】:2022-01-21 11:14:50
【问题描述】:

我收到错误无法将类型“()”的值转换为预期的参数类型“(() -> Void)?”同时使用执行操作 onAppear 功能。下面是代码。

这是显示图像/视频/PDF 文件的视图

struct AssetView: View {
    @ObservedObject var messageAttachmentViewModel: MessageAttachmentViewModel
    var index: Int
    var body: some View {
        let messageAttachmentModel = messageAttachmentViewModel.commonMessageAttachmentModel[index]
        switch messageAttachmentModel.uploadStatus {
        case .idle:
            Color.clear.onAppear(perform: messageAttachmentViewModel.uploadFileData(index: index)) // ERROR
        case .failed(let error):
            ProgressView()
        case .loading(let progress):
         //   print(progress)
            ProgressView(value: progress.fractionCompleted, total: Double(progress.totalUnitCount))
        case .loaded:
            ZStack(alignment: .trailing) {
                if messageAttachmentModel.assetType == .Photo {
                    PhotoView(messageAttachment: messageAttachmentModel)
                } else if messageAttachmentModel.assetType == .Video {
                    VideoView(messageAttachment: messageAttachmentModel)
                } else if messageAttachmentModel.assetType == .PDF {
                    PDFView(messageAttachment: messageAttachmentModel)
                }
            }
            .background(Color.red)
            .frame(width: 150, height: 150)
        }
    }
}

【问题讨论】:

  • onAppear 采用函数(闭包),而不是函数调用。你的意思是perform: {messageAttachmentViewModel.uploadFileData(index: index)})(注意花括号)

标签: xcode swiftui closures completionhandler


【解决方案1】:

将其放入显式闭包中,例如

case .idle:
    Color.clear.onAppear {
       messageAttachmentViewModel.uploadFileData(index: index)
    }

它报告错误,因为尝试将 messageAttachmentViewModel.uploadFileData() 的返回值(即 Void)转换为预期的无参数闭包。

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 2017-01-13
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多