5

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?>?'

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Sofiane Lyno
  • 165
  • 1
  • 10
  • This question is similar: [How to assign an optional Binding parameter in SwiftUI?](https://stackoverflow.com/questions/57163055/how-to-assign-an-optional-binding-parameter-in-swiftui) – pawello2222 Jun 05 '20 at 14:24
  • Yes but the accepted answer doesn't show how to call the constructor – Sofiane Lyno Jun 05 '20 at 14:25

1 Answers1

7

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("")
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690