Sofiane Lyno
Sofiane Lyno

Reputation: 185

Optional Binding in parameter SwiftUI

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

Upvotes: 5

Views: 4720

Answers (1)

Asperi
Asperi

Reputation: 257693

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("")
    }
}

Upvotes: 7

Related Questions