Last active
September 20, 2022 20:23
-
-
Save nmbr73/ae345c0836889b914931d6002ad9e177 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// Conversion | |
// | |
// Created by nmbr73 on 07.09.22. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
let units = ["secs","mins","hrs","days"] | |
let factors = [ 1.0, 60.0, 60.0 * 60.0, 60.0 * 60.0 * 24.0] | |
func factor(for unit: String) -> Double { | |
let unitIndex = units.firstIndex(of: unit) ?? 0 | |
return factors[unitIndex] | |
} | |
@State private var fromValue = 0 | |
@State private var fromUnit = "secs" | |
@State private var toUnit = "secs" | |
var toValue: Double { | |
let fromSeconds = Double(fromValue) * factor(for: fromUnit) | |
return fromSeconds / factor(for: toUnit) | |
} | |
var body: some View { | |
NavigationView { | |
Form { | |
Section { | |
TextField("Input Value", value: $fromValue, format: .number) | |
.keyboardType(.numberPad) | |
Picker("Unit", selection: $fromUnit) { | |
ForEach(units, id: \.self) { | |
Text($0) | |
} | |
} | |
.pickerStyle(.segmented) | |
} | |
footer: { Text("Enter a value and select its unit.") } | |
Section { | |
Text(String(toValue)) | |
Picker("Unit", selection: $toUnit) { | |
ForEach(units, id: \.self) { | |
Text($0) | |
} | |
} | |
.pickerStyle(.segmented) | |
} | |
footer: { Text("Select the unit used for the conversion.") } | |
} | |
.navigationTitle("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