Skip to content

Instantly share code, notes, and snippets.

@nmbr73
Last active September 20, 2022 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmbr73/ae345c0836889b914931d6002ad9e177 to your computer and use it in GitHub Desktop.
Save nmbr73/ae345c0836889b914931d6002ad9e177 to your computer and use it in GitHub Desktop.
//
// 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