I have an Asset SwiftData object with var cost: Int? in it.
I have this TextField() in my View:
TextField("realestate_cost_eg", value: $asset.cost, format: .number)
If $asset.cost = nil, as soon as this TextField gets focus the app crashes due to an IntegerParseStrategy.parse() error.
I know there are a lot of other questions/answers out there that refer to TextField(formatter: NumberFormatter()) solutions, but that initializer isn’t the recommended approach anymore. The recommended init is TextField(value: , format:).
And the documentation explicitly says this should work as I would expect it to work, i.e. it takes a binding to an optional, whenever the text changes it will try to parse it and set the value on the binding, but if it can’t parse it then it sets the value on the binding to nil:
https://developer.apple.com/documentation/swiftui/textfield/init(_:value:format:prompt:)-6ug7k
Use this initializer to create a text field that binds to a bound
optional value, using a ParseableFormatStyle to convert to and from
this type. Changes to the bound value update the string displayed by
the text field. Editing the text field updates the bound value, as
long as the format style can parse the text. If the format style can’t
parse the input, the text field sets the bound value to nil.
Instead, if $asset.cost is nil and the TextField() gets focus, then my app crashes with this stacktrace:





