I couldn't wrap my head around converting the units that had different scales (meters, feet, etc.) so I took the easy way out and did the time conversion. Although I guess maybe Swift has some built-in functions for converting things (looking at other people's solutions to this)?
Originally I spent awhile trying to get the two pickers to get their value and label from one dictionary, but couldn't figure it out and just kept getting a bunch of weird errors in Xcode that I didn't really know how to fix.
So I ended up using an array of units, and then a dictionary with keys to match the units values. Took me awhile to then figure out how to treat that lookup as an optional, but once I got that working then it all seemed to click.
I'd be interested to know if there is a way to populate the pickers using just the unitsDisplay dictionary directly vs. my hack of the units array as well.
Took a bit of trial and error but seems to work fairly well in the end. I'd appreciate any feedback or suggestions anybody has.
Thanks. SwiftUI is fun so far :)
struct ContentView: View {
@State private var inputUnit:Int = 1
@State private var outputUnit:Int = 1
@State private var inputNumber:Int = 1
@FocusState private var inputNumberIsFocused: Bool
let units = [1, 60, 3600, 86400]
let unitsDisplay = [
1 : "Seconds",
60 : "Minutes",
3600 : "Hours",
86400 : "Days"
]
var convertedNumber: Int {
let converted = inputNumber * inputUnit / outputUnit;
return converted
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Amount", value: $inputNumber, format: .number)
.keyboardType(.numberPad)
.focused($inputNumberIsFocused)
} header: {
Text("Number to Convert")
}
Section {
Picker("Input Units", selection: $inputUnit) {
ForEach(units, id: \.self) {
if let label = unitsDisplay[$0] {
Text(label)
}
}
}
.pickerStyle(.segmented)
} header: {
Text("Convert From")
}
Section {
Picker("Input Units", selection: $outputUnit) {
ForEach(units, id: \.self) {
if let label = unitsDisplay[$0] {
Text(label)
}
}
}
.pickerStyle(.segmented)
} header: {
Text("Convert To")
}
Section {
Text(convertedNumber, format: .number)
} header: {
Text("Converted Number")
}
}
.navigationTitle("Convert It!")
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
inputNumberIsFocused = false
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}