Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Time Turner
import SwiftUI
struct ContentView: View {
enum timeUnits: String, CaseIterable, Identifiable {
var id: String { self.rawValue }
case seconds = "seconds"
case minutes = "minutes"
case hours = "hours"
case days = "days"
}
@State private var input = ""
@State private var inputUnit: timeUnits = .seconds
@State private var outputUnit: timeUnits = .seconds
var inputInSeconds: Double {
let totalSeconds = Double(input) ?? 0
switch inputUnit {
case .seconds: return totalSeconds
case .minutes: return totalSeconds * 60
case .hours: return totalSeconds * 3600
case .days: return totalSeconds * 86_400
}
}
var convertedTime: Double {
switch outputUnit {
case .seconds: return self.inputInSeconds
case .minutes: return self.inputInSeconds / 60
case .hours: return self.inputInSeconds / 3600
case .days: return self.inputInSeconds / 86_400
}
}
var body: some View {
NavigationView {
Form {
Section(header: Text("Time to convert")) {
TextField("Enter an amount to convert…", text: $input)
.keyboardType(.decimalPad)
Picker("Input Unit", selection: $inputUnit) {
ForEach(timeUnits.allCases) {
Text($0.rawValue).tag($0)
}
}
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Converted Time")) {
Text("\(convertedTime, specifier: convertedTime.truncatingRemainder(dividingBy: 1) == 0 ? "%.f" : "%.5f")")
Picker("Output Unit", selection: $outputUnit) {
ForEach(timeUnits.allCases) {
Text($0.rawValue).tag($0)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
.navigationBarTitle("Time Turner")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice("iPhone 11 Pro")
}
}
@k-mao

This comment has been minimized.

Copy link
Owner Author

@k-mao k-mao commented Sep 14, 2020

My first SwiftUI app coded on my own! This app converts time between seconds, minutes, hours, and days.

This is from Day 19 - Challenge Day of @twostraws' 100 Days of SwiftUI.

@k-mao

This comment has been minimized.

Copy link
Owner Author

@k-mao k-mao commented Sep 15, 2020

Another iteration on this, just for fun: https://gist.github.com/k-mao/e7a863937b9d06cfec4ed0ba156be743

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment