Created
March 10, 2023 14:46
-
-
Save shaps80/7fedbefaf506c391a567bf738fe10cfb to your computer and use it in GitHub Desktop.
Convert SwiftUI Optional Binding to Non-Optional Binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Binding { | |
public init(wrappedValue: Binding<Value?>, defaultValue: Value) { | |
self = Binding<Value>( | |
get: { wrappedValue.wrappedValue ?? defaultValue }, | |
set: { wrappedValue.wrappedValue = $0 } | |
) | |
} | |
public func defaultValue<T>(_ value: T) -> Binding<T> where Value == T? { | |
Binding<T>( | |
get: { wrappedValue ?? value }, | |
set: { wrappedValue = $0 } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Particularly useful when dealing with CoreData objects: