Last active
March 24, 2025 17:04
-
-
Save StewartLynch/8a4511d6f3525a55fcfe6fb005566f16 to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
extension Binding { | |
/// Binding to an optional value by providing a defatult value. | |
/// | |
/// example | |
/// | |
/// struct Sample: View { | |
/// @Binding var name: String? | |
/// | |
/// var body: some View { | |
/// TextField("Name", text: .init($name, defaultValue: "")) | |
/// } | |
/// } | |
/// Creates a Binding<Value>' for an optional value with a default. | |
/// - Parameters: | |
/// - optionalBinding: A binding to an optional value. | |
/// - defaultValue: The default value to use when the optional is nil'. | |
/// | |
init(_ optionalBinding: Binding<Value?>, defaultValue: Value) where Value: Sendable { | |
self.init( | |
get: {optionalBinding.wrappedValue ?? defaultValue}, | |
set: {newValue in | |
optionalBinding.wrappedValue = newValue | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment