英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论