You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何解决‘无法将Void转为() -> Void’类型转换错误?

问题解决

错误原因

你当前写的helloVM.hello()是直接调用了hello方法,会执行方法内逻辑并返回Void(空值),但test2的action参数需要的是一个函数类型() -> Void(即后续可被调用的闭包),而非函数执行后的结果,因此出现类型不匹配的编译错误。

解决方案

方案一:无需修改HelloViewModel(推荐)

调整test1中传递参数的方式,去掉hello()的括号,直接传递方法引用:

struct test1: View {
    @ObservedObject var helloVM = HelloViewModel()

    var body: some View{
       test2(action: helloVM.hello) // 传递方法引用,而非执行方法
    }
}

方案二:修改HelloViewModel的hello方法

如果一定要改动hello()方法,可以让它返回一个() -> Void类型的闭包,这样调用helloVM.hello()时会得到符合要求的闭包:

class HelloViewModel: ObservableObject{
     func hello() -> () -> Void {
         return {
             print("hello")
         }
     }
}

这种情况下,test1的原有代码无需改动即可正常编译。

内容的提问来源于stack exchange,提问作者Taro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:38:22