How should I resolve Cannot convert value of type 'Void' to expected argument type '() -> Void' by SwiftUI

huangapple go评论137阅读模式
英文:

How should I resolve Cannot convert value of type 'Void' to expected argument type '() -> Void' by SwiftUI

问题

I want to pass helloVM.hello() to test2 view's action.
But then I got this error Cannot convert value of type 'Void' to expected argument type '() -> Void' at test2(action: helloVM.hello()) in test1.

How should I fix HelloViewModel's hello()?

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

    var body: some View{
       test2(action: helloVM.hello())
    }
}
struct test2: View {
    let action: () -> Void

    var body: some View{
       Button(action: {
                  action()
              }, label: {
                  Text("hello")
               })
    }
}
class HelloViewModel: ObservableObject{
     func hello() -> Void{
         print("hello")
     }
}

I think hello() doesn't have any argument and returns Void.
But the compiler says such an error.

Thank you

英文:

I want to pass helloVM.hello() to test2 view's action.
But then I got this error Cannot convert value of type 'Void' to expected argument type '() -> Void' at test2(action: helloVM.hello()) in test1.

How should I fix HelloViewModel's hello()?

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

    var body: some View{
       test2(action: helloVM.hello())
    }
}
struct test2: View {
    let action: ()-> Void

    var body: some View{
       Button(action: {
                  action()
              }, label: {
                  Text("hello")
               })
    }
}
class HelloViewModel: ObservableObject{
     func hello() -> Void{
         print("hello")
     }
}

I think hello() don't have any argument and return Void.
But compiler says such error.

Thank you

答案1

得分: 1

test2(action: helloVM.hello) 移除括号。

这是因为。

() -> Void 表示 "返回 Void 的函数"。

执行 helloVM.hello() 函数并返回一个值。

您想返回函数本身,而不是函数的返回值。

英文:

test2(action: helloVM.hello) remove the parenthesis

This is because.

() -> Void means "function that returns Void"

helloVM.hello()

Runs the function and returns a value.

You want to return the function, not the return of the function.

huangapple
  • 本文由 发表于 2023年3月9日 21:38:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定