Skip to content

Instantly share code, notes, and snippets.

@jancassio
Last active October 16, 2022 01:40
Show Gist options
  • Save jancassio/7d7d9809493a8bbe549b7ab1e1229707 to your computer and use it in GitHub Desktop.
Save jancassio/7d7d9809493a8bbe549b7ab1e1229707 to your computer and use it in GitHub Desktop.
BindingUnwrapperView

BindingUnwrapperView

⚠️ WARNING ⚠️

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.

Use case

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.

Usage

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

License

MIT

/*
BindingUnwrapperView.swift
MIT License
Copyright (c) 2022 Jan Cassio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import SwiftUI
struct BindingUnwrapperView<Content, Value>: View where Content: View {
@Binding var value: Value?
let content: (Binding<Value>) -> Content
let fallback: () -> Content
private var resolved: Binding<Value>? {
guard let value else {
return nil
}
return Binding(
get: { value },
set: { newValue in self.value = newValue }
)
}
init(
_ value: Binding<Value?>,
@ViewBuilder content: @escaping (Binding<Value>) -> Content,
@ViewBuilder fallback: @escaping () -> Content
) {
self._value = value
self.content = content
self.fallback = fallback
}
var body: some View {
if let resolved {
content(resolved)
} else {
fallback()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment