For Day 19 Challenge, Paul suggests trying to format the unit conversion output..."if you’d like to be a bit fancy with the output number you display, try calling .formatted() on it – e.g. someDouble.formatted(). This will cause iOS to format the number for printing, adding thousands separator and removing a lot of the noise from unnecessary decimal places."
I've tried adding .formated() to my output text field (in 4th section) but keep getting errors (see //comments in code). How would I use .formatted with my output text box to get the result Paul suggests?
struct ContentView: View {
@State private var conversionValue = 0.0
@State private var inputUnit = "meters"
@State private var outputUnit = "feet"
@FocusState private var valueIsFocused: Bool
let inputUnitSelection = ["feet", "yards", "miles", "meters", "kilometers"]
let outputUnitSelection = ["feet", "yards", "miles", "meters", "kilometers"]
var baseUnitValue: Double {
var value = 0.0
switch inputUnit {
case "feet":
value = conversionValue / 3.28084
return value
case "yards":
value = conversionValue / 3
return value
case "miles":
value = conversionValue / 5280
return value
case "meters":
value = conversionValue * 1
return value
default:
value = conversionValue / 1000
return value
}
}
var convertedValue: Double {
var value = 0.0
switch outputUnit {
case "feet":
value = baseUnitValue * 3.28084
return value
case "yards":
value = baseUnitValue * 1.093613
return value
case "miles":
value = baseUnitValue * 0.0006213712
return value
case "meters":
value = baseUnitValue * 1
return value
default:
value = baseUnitValue / 1000
return value
}
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Value to convert", value: $conversionValue, format: .number)
.keyboardType(.decimalPad)
.focused($valueIsFocused)
} header: {
Text("Enter conversion value")
}
Section {
Picker("Unit", selection: $inputUnit) {
ForEach(inputUnitSelection, id: \.self) {
Text($0)
}
}
} header: {
Text("Select unit to convert from")
}
Section {
Picker("Unit", selection: $outputUnit) {
ForEach(outputUnitSelection, id: \.self) {
Text($0)
}
}
} header: {
Text("Select unit to convert to")
}
Section {
Text(convertedValue, format: .number) //Tried format: .formatted() and number.formatted() but gives error
// .formatted() here gives errors
} header: {
Text("Converted value")
}
}
.navigationTitle("Unit Converter")
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
valueIsFocused = false
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}