Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created February 7, 2023 17:03
Show Gist options
  • Save andresr-dev/799f7b7295e437f2c6f7221efa084851 to your computer and use it in GitHub Desktop.
Save andresr-dev/799f7b7295e437f2c6f7221efa084851 to your computer and use it in GitHub Desktop.
This is a custom operator that allows you to perform nil coalescing with optional bindings in swift
import SwiftUI
public func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
Binding(
get: { lhs.wrappedValue ?? rhs },
set: { lhs.wrappedValue = $0 }
)
}
// MARK: - USE
struct ContentView: View {
@State private var name: String?
var body: some View {
TextField("Name", text: $name ?? "")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment