I have the textField with optional Int value.
But when I changed the int value, the textField is not being updated.
The code is like below.
@State private var amount: Double?
var body: some View {
VStack {
TextField(value: $amount, format: .number) {
Text("$0")
}
Button("reset") {
reset()
}
}
}
private func reset() {
amount = nil
}
I want to textField value to nil when the button is tapped.
But the above code is not working.
What could be the problem?
2
Answers
You’re displaying the hardcoded string
"$0"
– you aren’t actually using the closure value. You need to use string interpolation to display the actual closure value.You also need to decide what to display in case
amount
isnil
. Below example displays0
whenamount
isnil
.Using named closure arguments helps you avoid similar issues in the future, since if you don’t use the named closure argument, you get a compiler warning.
You could also display the
String
"nil"
in caseamount
isnil
:You can’t set the variable
amount
to nil becauseamount
is aDouble
You’ll get this error : ‘nil’ cannot be assigned to type "Double"And this code
Text("$0")
isn’t correct. If you want to displayamount
, you have to useText("(amount)")