Last active
September 15, 2020 10:42
-
-
Save k-mao/ed6abad17449ad3770ea2d6059712646 to your computer and use it in GitHub Desktop.
Time Turner
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
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") | |
} | |
} |
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
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.