Optional Binding in parameter SwiftUI

妖精的绣舞 提交于 2020-11-29 10:40:15

问题


Here are my optional binding

@Binding var showSheetModifFile : Bool?
@Binding var fileToModify : File?

init( showSheetModifFile : Binding<Bool?>? = nil, fileToModify : Binding<File?>? = nil) {
    _showSheetModifFile = showSheetModifFile ?? Binding.constant(nil)
    _fileToModify = fileToModify ?? Binding.constant(nil)
}    

So now when I try to call this constructor:

@State var showModifFileSheet : Bool? = false
@State var fileToModify : File? = File()
...

SingleFileView(showSheetModifFile: self.$showModifFileSheet, fileToModify: self.$fileToModify)

I got this error:

'Binding<Bool?>' is not convertible to 'Binding<Bool?>?'


回答1:


There is special Binding constructor for this purpose

SingleFileView(showSheetModifFile: Binding(self.$showModifFileSheet), 
   fileToModify: Binding(self.$fileToModify))

Update: alternate solution

struct FileDemoView: View {
    @State var showModifFileSheet : Bool? = false
    @State var fileToModify : File? = File()

    var body: some View {
        SingleFileView(showSheetModifFile: $showModifFileSheet, fileToModify: $fileToModify)
    }

}


struct SingleFileView: View {
    @Binding var showSheetModifFile : Bool?
    @Binding var fileToModify : File?


    init(showSheetModifFile : Binding<Bool?> = .constant(nil), fileToModify : Binding<File?> = .constant(nil)) {
        _showSheetModifFile = showSheetModifFile
        _fileToModify = fileToModify
    }

    var body: some View {
        Text("")
    }
}


来源:https://stackoverflow.com/questions/62217349/optional-binding-in-parameter-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!