I just completed coding the Day 19 challenge and I got it to work it appears. I chose to code for the unit of measure length.
When reading the Picker selections for starting and ending UofM I tried to use a switch statements with cases for each picker selection but couldn't get it to build; so eventually abandoned the effort and used If statements instead which works.
Is it possible to use a switch statement instead of If statements? If so how would it be coded?
Much appreciated in advance.
My code follows...
import SwiftUI
struct ContentView: View {
@State private var inputValue = 0.0
@State private var inputUnit = ""
@State private var outputUnit = ""
var unitsOfMeasure = ["meter","kilomtr", "feet", "yard", "mile"]
@FocusState private var inputFieldIsFocused: Bool
var baseUnitValue: Double {
var valueOfBaseUnit = 0.0
if inputUnit == "kilomtr" {
valueOfBaseUnit = inputValue * 1000
} else if inputUnit == "feet" {
valueOfBaseUnit = inputValue / 3.2808
} else if inputUnit == "yard" {
valueOfBaseUnit = inputValue / 1.0936
} else if inputUnit == "mile" {
valueOfBaseUnit = inputValue / 0.00062137
} else {
valueOfBaseUnit = inputValue
}
return valueOfBaseUnit
}
var outputValue: Double {
var valueOfOutput = 0.0
if outputUnit == "meter" {
valueOfOutput = baseUnitValue
} else if outputUnit == "kilomtr" {
valueOfOutput = baseUnitValue / 1000
} else if outputUnit == "feet" {
valueOfOutput = baseUnitValue * 3.2808
} else if outputUnit == "yard" {
valueOfOutput = baseUnitValue * 1.0936
} else {
valueOfOutput = baseUnitValue * 0.00062137
}
return valueOfOutput
}
var body: some View {
NavigationView {
Form {
Section {
Picker("Starting Unit", selection: $inputUnit) {
ForEach(unitsOfMeasure, id: \.self) {
Text($0)
}
} .pickerStyle(.segmented)
}
header: {
Text("Select the starting unit of measurement")
}
Section {
Picker("Ending Unit", selection: $outputUnit) {
ForEach(unitsOfMeasure, id: \.self) {
Text($0)
}
}.pickerStyle(.segmented)
}
header: {
Text("Select the ending unit of measurement")
}
Section {
TextField("Enter a value to convert", value: $inputValue, format: .number)
.keyboardType(.decimalPad)
.focused($inputFieldIsFocused)
}
header: {
Text("Enter a value to convert")
}
Section {
Text(outputValue, format: .number)
}
header: {
Text("The converted value")
}
}
.navigationTitle("UnitConverter")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
inputFieldIsFocused = false
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}