I’m currently working my way through Paul Hudson’s 100 Days of SwiftUI.
On Day 19, there’s a challenge to create a unit conversion app.
I’ve cobbled something together and it works but it almost certainly can be improved and in the name of learning I’d love to know how. Any help would be gratefully received.
let units = ["Celsius", "Fahrenheit", "Kelvin"]
@State private var fromUnit = "Celsius"
@State private var toUnit = "Fahrenheit"
@State private var inputValue = 0.0
@FocusState private var entryIsFocused: Bool
var resultValue: String {
var endUnit: String {
var resultUnits = String()
if toUnit == "Fahrenheit" {
resultUnits = "°F"
} else if toUnit == "Kelvin" {
resultUnits = " K"
} else {
resultUnits = "°C"
}
return resultUnits
}
var convertingTo = Double()
if fromUnit == toUnit {
convertingTo = inputValue
} else {
var convertingFrom = Double()
if fromUnit == "Fahrenheit" {
convertingFrom = ( inputValue - 32 ) / 1.8
} else if fromUnit == "Kelvin" {
convertingFrom = inputValue - 273.15
} else {
convertingFrom = inputValue
}
// The conversion
if toUnit == "Fahrenheit" {
convertingTo = convertingFrom * 1.8 + 32
} else if toUnit == "Kelvin" {
convertingTo = convertingFrom + 273.15
} else {
convertingTo = convertingFrom
}
}
let result = String(format: "%.1f\(endUnit)", convertingTo)
return result
}