First things first. Paul, you are awesome! I never thought, that I start programming on XCode ever...
Love your videos and the way you make things clear. Even as a non-native english speaker, I can follow your descriptions.
Here is my solution:
//
// ContentView.swift
// Converter Liquids
//
// Created by Oliver Kleemann on 05.04.22.
//
import SwiftUI
struct ContentView: View {
@State private var from: String = "Liter"
@State private var to: String = "Liter"
@State private var value: Double = 1.0
// add more units into this dictionary here:
let units = ["Liter": 1.0,
"Milliliter": 1000.0,
"Hektoliter": 0.01,
"Kubikmeter": 0.001,
"US-Gallone": 0.264172,
"US-Quart": 1.05669,
"US-Pint": 2.11338,
"US-Cup": 4.16667,
"UK-Gallone": 0.219969,
"UK-Quart": 0.879877,
"UK-Pint": 1.75975,
"UK-Cup": 3.51951]
// this is the array used for the both pickers
var unitArray: [String] {
var outputArray: [String] = []
for unit in units { outputArray.append(unit.key) }
return outputArray
}
var conversionResult: Double {
let fromFactor = units[from] ?? 0.0
let toFactor = units[to] ?? 0.0
return value / fromFactor * toFactor
}
var body: some View {
NavigationView {
Form {
Section {
Picker("From unit:", selection: $from) {
ForEach (unitArray.sorted(), id: \.self) {
Text ($0)
}
.pickerStyle(.automatic)
}
TextField ("Value to convert", value: $value, format: .number)
.keyboardType(.decimalPad)
} header: { Text("Input") }
HStack{
Spacer()
// exchange the units
Button ("↕️"){
let exchange = from
from = to
to = exchange
}
Spacer()
}
Section {
Picker("To unit:", selection: $to) {
ForEach (unitArray.sorted(), id: \.self) {
Text ($0)
}
.pickerStyle(.automatic)
}
Text (conversionResult, format: .number)
} header: { Text ("Result") }
}
.navigationTitle("Liquid Converter")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewInterfaceOrientation(.portrait)
}
}
Took me a long time, but with the knowledge of WeSplit, the goal was reachable.
A lot to learn ...
Thanks for your great work!