Skip to content

Instantly share code, notes, and snippets.

@k-mao
Last active September 15, 2020 10:42
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 k-mao/ed6abad17449ad3770ea2d6059712646 to your computer and use it in GitHub Desktop.
Save k-mao/ed6abad17449ad3770ea2d6059712646 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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