Skip to content

Instantly share code, notes, and snippets.

@maartene
Last active October 11, 2019 19:55
Show Gist options
  • Save maartene/fd9659c1bb5846ab8f7a179ee9ad21d6 to your computer and use it in GitHub Desktop.
Save maartene/fd9659c1bb5846ab8f7a179ee9ad21d6 to your computer and use it in GitHub Desktop.
Day 19 challenge of "100 days of Swift UI" - length converter
//
// ContentView.swift
// Conversions
//
// Created by Maarten Engels on 11/10/2019.
// Copyright © 2019 thedreamweb. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var inputAmount = ""
@State var fromConversionIndex = 1
@State var toConversionIndex = 3
let units: [(unitName: String, conversionRate: Double)] = [("mm", 0.001), ("m", 1.0), ("km", 1000), ("inch", 0.0254), ("foot", 0.3048), ("yard", 0.9144), ("mile", 1_609.344)]
var inputValue: Double {
return Double(inputAmount) ?? 0
}
var unitAmount: Double {
let unit = units[fromConversionIndex]
return inputValue * unit.conversionRate
}
var convertedAmount: Double {
let unit = units[toConversionIndex]
return unitAmount / unit.conversionRate
}
var body: some View {
NavigationView {
Form {
Section(header: Text("Convert")) {
TextField("Amount to convert", text: $inputAmount)
.keyboardType(.decimalPad)
Picker("from unit", selection: $fromConversionIndex) {
ForEach(0 ..< units.count) {
Text("\(self.units[$0].unitName)")
}
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("To")) {
Picker("To unit", selection: $toConversionIndex) {
ForEach(0 ..< units.count) {
Text("\(self.units[$0].unitName)")
}
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Converted value")) {
Text("\(inputValue == 1337 ? "h4x0r!" : String(convertedAmount))")
}
}.navigationBarTitle("Conversions")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@maartene
Copy link
Author

This is a simple solution to the first challenge of "100 days of SwiftUI": write a unit conversion application. It's not clever by any means, but at least it has an Easter egg :)

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