You don't want to be creating a new Binding
every body
load. Use a custom ParseableFormatStyle
instead.
struct OptionalStringParseableFormatStyle: ParseableFormatStyle {
var parseStrategy: Strategy = .init()
func format(_ value: String?) -> String {
value ?? ""
}
struct Strategy: ParseStrategy {
func parse(_ value: String) throws -> String? {
guard !value.isEmpty else {
return nil // How to handle empty/nil is up to the developer.
}
return value
}
}
}
Then use it
TextField("My Label", value: $myValue, format: OptionalStringParseableFormatStyle())
Make It Generic
I prefer to make generic versions of these styles with static conveniences that can work with any type.
extension Optional {
struct FormatStyle<Format: ParseableFormatStyle>: ParseableFormatStyle
where Format.FormatOutput == String, Format.FormatInput == Wrapped {
let formatter: Format
let parseStrategy: Strategy<Format.Strategy>
init(format: Format) {
self.formatter = format
self.parseStrategy = .init(strategy: format.parseStrategy)
}
func format(_ value: Format.FormatInput?) -> Format.FormatOutput {
guard let value else { return "" }
return formatter.format(value)
}
struct Strategy<OutputStrategy: ParseStrategy>: ParseStrategy where OutputStrategy.ParseInput == String {
let strategy: OutputStrategy
func parse(_ value: String) throws -> OutputStrategy.ParseOutput? {
guard !value.isEmpty else { return nil }
return try strategy.parse(value)
}
}
}
}
extension ParseableFormatStyle where FormatOutput == String {
var optional: Optional<FormatInput>.FormatStyle<Self> { .init(format: self) }
}
String does not have a format style as it is redundant in most cases so I make an identity ParseableFormatStyle
extension String {
struct FormatStyle: ParseableFormatStyle {
var parseStrategy: Strategy = .init()
func format(_ value: String) -> String {
value
}
struct Strategy: ParseStrategy {
func parse(_ value: String) throws -> String {
value
}
}
}
}
extension ParseableFormatStyle where Self == String.FormatStyle {
static var string: Self { .init() }
}
extension ParseableFormatStyle where Self == Optional<String>.FormatStyle<String.FormatStyle> {
static var optional: Self { .init(format: .string) }
}
Now you can use this for any value. Examples:
TextField("My Label", value: $myStringValue, format: .optional)
TextField("My Label", value: $myStringValue, format: .string.optional)
TextField("My Label", value: $myNumberValue, format: .number.optional)
TextField("My Label", value: $myDateValue, format: .dateTime.optional)
@State var test = ""
? If not, then what do you want with theTextField
when your string isnil
?