Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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() don’t have any argument and return Void.
But compiler says such error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading