Skip to content

Instantly share code, notes, and snippets.

@Gujci
Created October 14, 2019 21:39
Show Gist options
  • Save Gujci/91d8a72225425c5325ca108cc9494ae8 to your computer and use it in GitHub Desktop.
Save Gujci/91d8a72225425c5325ca108cc9494ae8 to your computer and use it in GitHub Desktop.
import SwiftUI
extension String: Identifiable {
public var id: String { self }
}
struct ContentView: View {
@State private var baseNumber = ""
@State private var dimensionSelection: String = ""
@State private var baseUnitSelection: String = ""
@State private var convertedUnitSelection: String = ""
let temperatureUnits: [String] = ["Celsius", "Fahrenheit", "Kelvin"]
let lengthUnits: [String] = ["meters", "kilometers", "feet", "yards", "miles"]
let timeUnits: [String] = ["seconds", "minutes", "hours", "days"]
let volumeUnits: [String] = ["milliliters", "liters", "cups", "pints", "gallons"]
let dimensionChoices: [String] = ["Temperature", "Length", "Time", "Volume"]
let dimensions: [(String, [String])]
init () {
dimensions = zip(dimensionChoices, [temperatureUnits, lengthUnits, timeUnits, volumeUnits])
.reduce([], { acc, val in acc + [(val.0, val.1)] })
}
var convertedValue: Double {
var result: Double = 0
let base = Double(baseNumber) ?? 0
if baseUnitSelection == "Celsius" {
if convertedUnitSelection == "Celsius" {
result = base
} else if convertedUnitSelection == "Fahrenheit" {
result = base * 9/5 + 32
} else if convertedUnitSelection == "Kelvin" {
result = base + 273.15
}
}
return result
}
var dimensionUnitsView: some View {
(dimensions.first(where: {(key, _) in key == dimensionSelection })?.1).map { options in
Group {
Section(header: Text("Select the base unit")) {
Picker("Base Unit", selection: self.$baseUnitSelection) {
ForEach(options) { selection in
Text(selection)
}
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Select the unit to convert to")) {
Picker("Converted Unit", selection: self.$convertedUnitSelection) {
ForEach(options) { selection in
Text(selection)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
}
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Enter a number", text: $baseNumber)
.keyboardType(.decimalPad)
}
Section(header: Text("Select the type of conversion")) {
Picker("Dimension", selection: $dimensionSelection) {
ForEach(dimensions.map({ $0.0 })) { dimension in
Text(dimension)
}
}.pickerStyle(SegmentedPickerStyle())
}
dimensionUnitsView
Section(header: Text("The converted value is")) {
Text("\(convertedValue)")
}
}.navigationBarTitle("Unit Converter")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment