This concept still not working and I don't have a clue (so far) why it do not compile because the only error I get is:
failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
BindingUnwrapperView is a view that safely turns a Binding<Value?> into a Binding<Value> and when it fails, provides a fallback block that can be used to return some View.
Some views can have Binding<Value> fields (for example @Binding var Todo), where the Value can be a struct that has optional fields.
Maybe, the field is desirable to be a bind of some other component, for example a TextField where text should be a Binding<String>.
BindingUnwrapperView enable to safely bind optional fields of a struct in case the value is not nil, so the TextField or any other View that expects a non optional Value, can be conditioned to rendered.
For a more concrete example, see next the topic below.
struct Todo {
var text: String
var checked: Bool = false
var due: Date? // notice due is optional
}
struct TodoView: View {
@Binding var todo: Todo // This todo will not by optional but todo.due is
var body: some View {
VStack {
HStack {
TextField("text", text: $todo.text)
Button {
withAnimation {
todo.checked.toggle()
}
} label: {
if todo.checked {
Image(systemName: "checkmark.square")
} else {
Image(systemName: "square")
}
}
}
BindingUnwrapperView($todo.due) { $due in // BindingUnwrapper view proviedes a Binding<Date> instead of Binding<Date?>...
DatePicker("Due", selection: $due) // ...So it can be safely bindinde with DataPicker's selection prop...
} fallback: { // ...otherwise, render something else.
Text("")
.font(.caption)
.foregroundColor(.gray)
}
}
}
}MIT