Reputation: 91
When I enter the number both on a and b, suppose 58 and 78 in the text field. And then when I go back to clear the number a, and come to number b, the number a value shows up with 5 instead of 0, is there anyway I can get this fixed to show a 0 value when the number is cleared instead of showing 5? Here's is the code.
import SwiftUI
struct ContentView: View {
@State var a = Double()
@State var b = Double()
var body: some View {
HStack {
Text("Number 1")
TextField("Enter Number 1", value: $a, format: .percent)
}
HStack {
Text("Number 2")
TextField("Enter Number 2", value: $b, format: .percent)
}
}
}
Upvotes: 1
Views: 964
Reputation: 3051
You can try this way.
struct ContentView: View {
@State var a: Double?
@State var b: Double?
@State var result : Double = 0.0
var body: some View {
HStack {
Text("Number 1")
TextField("Enter Number 1", value: $a, format: .percent)
}
HStack {
Text("Number 2")
TextField("Enter Number 2", value: $b, format: .percent)
}
HStack {
Button {
result = (a ?? 0.0) * (b ?? 0.0)
} label: {
Text("calculate a * b")
}
Text("\(result)")
}
}
}
Upvotes: 0
Reputation: 2859
The values bound to the text field have the type Double
and they can't ever be empty.
Here's what happens:
"58"
into the text field. The binding from the text field to the state var updates its value to 58.0
."5"
and the state var gets updated with the new value of 5.0
.nil
. SwiftUI tries updating the state var with the value of nil
, but it can't because its type is Double
, so the state var keeps the previous value of 5.0
.To fix it, change the type of the state vars to optional:
@State var a: Double?
@State var b: Double?
Upvotes: 1