Hi there,
As part of the Day 18 wrap-up challenge, I changed the Number of People field from a Picker to a Text Field. After doing so, the Amount Per Person displays "$-NaN" until you enter values for the Check Amount and Number of People fields.
I'm handling that Number of People text field in the same way as the Check Amount field by converting the String to a Double. But for some reason I'm getting a different result.
Has anyone run into this before or can spot what I'm doing wrong?
Many thanks!
Patrick
Screen recording of the issue
import SwiftUI
struct ContentView: View {
@State private var checkAmount = ""
@State private var numberOfPeople = ""
@State private var tipPercentage = 2
let tipPercentages = [10, 15, 20, 25, 0]
var checkTotal: Double {
let orderAmount = Double(checkAmount) ?? 0
let tipSelection = Double(tipPercentages[tipPercentage])
let tipValue = orderAmount / 100 * tipSelection
let totalWithTip = orderAmount + tipValue
return totalWithTip
}
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople) ?? 0
let tipSelection = Double(tipPercentages[tipPercentage])
let orderAmount = Double(checkAmount) ?? 0
let tipValue = orderAmount / 100 * tipSelection
let grandTotal = orderAmount + tipValue
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Enter Check Amount", text: $checkAmount)
.keyboardType(/*@START_MENU_TOKEN@*/.decimalPad/*@END_MENU_TOKEN@*/)
TextField("Enter Number of People", text: $numberOfPeople)
.keyboardType(/*@START_MENU_TOKEN@*/.decimalPad/*@END_MENU_TOKEN@*/)
}
Section(header: Text("How much tip do you want to leave?")) {
Picker("Tip Percentage", selection: $tipPercentage) {
ForEach(0 ..< tipPercentages.count) {
Text("\(self.tipPercentages[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Check Total")) {
Text("$\(checkTotal, specifier: "%.2f")")
}
Section(header: Text("Amount Per Person")) {
Text("$\(totalPerPerson, specifier: "%.2f")")
}
}
.navigationBarTitle("WeSplit")
}
}
}