Advertisements
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
>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.