import SwiftUI
struct ContentView: View {
@State private var value = 42.0
@State private var type = ConversionType.temperature
@State private var tempForm = UnitTemperature.celsius
@State private var tempTo = UnitTemperature.fahrenheit
@State private var lengthForm = UnitLength.meters
@State private var lengthTo = UnitLength.kilometers
@State private var timeForm = UnitDuration.nanoseconds
@State private var timeTo = UnitDuration.seconds
@FocusState private var isFocused
private enum ConversionType: String, CaseIterable {
case temperature = "🌡️"
case length = "📏"
case time = "⏱️"
}
private var result: String {
switch type {
case .temperature:
Measurement(value: value, unit: tempForm).converted(to: tempTo).description
case .length:
Measurement(value: value, unit: lengthForm).converted(to: lengthTo).description
case .time:
Measurement(value: value, unit: timeForm).converted(to: timeTo).description
}
}
var body: some View {
Form {
Section("Conversion Value") {
TextField("Value", value: $value, format: .number)
.keyboardType(.decimalPad)
.focused($isFocused)
}
Section("What do you want to convert?") {
Picker("", selection: $type) {
ForEach(ConversionType.allCases, id: \.self) {
Text($0.rawValue)
.font(.largeTitle)
}
}
.pickerStyle(.segmented)
}
Section("From") {
switch type {
case .temperature:
Picker("", selection: $tempForm) {
ForEach(UnitTemperature.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
case .length:
Picker("", selection: $lengthForm) {
ForEach(UnitLength.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
case .time:
Picker("", selection: $timeForm) {
ForEach(UnitDuration.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
}
}
Section(header: Text("To")) {
switch type {
case .temperature:
Picker("", selection: $tempTo) {
ForEach(UnitTemperature.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
case .length:
Picker("", selection: $lengthTo) {
ForEach(UnitLength.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
case .time:
Picker("", selection: $timeTo) {
ForEach(UnitDuration.cases, id: \.self) {
Text($0.symbol)
}
}
.pickerStyle(.segmented)
}
}
Section("Result") {
Text(result)
}
}
}
}
extension UnitTemperature {
public static var cases: [UnitTemperature] {
return [.celsius, .fahrenheit, .kelvin]
}
}
extension UnitLength {
public static var cases: [UnitLength] {
return [.meters, .kilometers, .feet, .yards, .miles]
}
}
extension UnitDuration {
public static var cases: [UnitDuration] {
return [.nanoseconds, .seconds, .minutes, .hours]
}
}
#Preview {
ContentView()
}