Swift:修复‘Cannot call value of non-function type `Binding<() -> ()>`’错误及函数定义
Swift Binding 错误解析与函数定义说明
1. 错误含义
这个错误说明你试图调用的showContents并非函数类型,而是一个Binding<() -> ()>类型的值——也就是说你实际传入的参数是绑定了一个无参无返回值的函数,而非代码声明中预期的Binding<Bool>。此时调用.toggle()时,编译器会认为你在尝试执行一个非函数类型的变量,因此报错。
2. 正确定义接收Binding<A>参数的ToolbarContent函数
要定义这类函数,核心是保证参数类型与实际传入值匹配,同时正确使用Binding包裹的类型方法。以下是修正后的示例代码:
@ToolbarContentBuilder func toolbarContent(displayMode: Binding<Bool>, showContents: Binding<Bool>) -> some ToolbarContent { ToolbarItem(placement: .navigationBarTrailing) { HStack { Picker("Display Mode", selection: displayMode) { Image(systemName: "rectangle.portrait").tag(true) Image(systemName: "rectangle.split.2x1").tag(false) }.pickerStyle(.segmented) } } ToolbarItem(placement: .navigationBarTrailing) { Button { // 当showContents为Binding<Bool>时,直接调用toggle()即可 showContents.toggle() // 也可以手动访问wrappedValue修改:showContents.wrappedValue.toggle() } label: { Image(systemName: "list.bullet.rectangle.fill") } } }
关键注意事项
- 调用函数时,传入的
showContents必须是Binding<Bool>类型,比如@State属性的$投影(如$isShowingContents),或是@Binding属性本身,不能传入绑定了函数的Binding。 - 只要
Binding包裹的类型(比如这里的Bool)拥有对应的方法(如toggle()),就可以直接通过Binding实例调用,编译器会自动处理对wrappedValue的访问。
内容的提问来源于stack exchange,提问作者F. Zer
相关产品推荐
相关产品推荐

