100 Days of SwiftUI — Day 19

Today, at Day 19 was the challenge day — and it was great! Basically, you had to build a unit conversion-app from scratch. Paul gave some examples on units and some tips and tricks — and then you were on your own.

As I enjoyed going to pubs in the UK in pre-corona-times from time to time, I decided to find out, how much I drank in liters (or litres?!) when I had four (imperial) pints. It's 2.27l — that's quite a lot! 🍺🍺🍺🍺

And this is, what the app looks like. Not really pretty, but it get's the job done:

I learned, that there's a built-in unit conversion in Foundation called (NS)Measurement. I didn't expect that, but wow, that's great! So the code to convert pints into litres (or liters) is pretty straightforward:

var convertedAmount: Double? {
  guard let amount = Double(amount) else { return nil }

  let input = Measurement(value: amount, unit: units[inputUnitIndex].unit)
  let output = input.converted(to: units[outputUnitIndex].unit)

  return output.value

units are an array of type: [(title: String, unit: UnitVolume)] so that I can show a nicer text in the pickers instead of only the symbol:

private let units: [(title: String, unit: UnitVolume)] = [
  (title: "Milliliters", unit: .milliliters),
  (title:"Liters", unit: .liters),
  (title: "Cups", unit: .cups),
  (title: "Pints", unit: .imperialPints),
  (title: "Gallons", unit: .imperialGallons),

I learned, that I can't use the fancy string formatting in string interpolation in computed variables, unfortunately. The SwiftUI itself is a Form with some Sections, nothing special.

I enjoyed today's task and again: I'm looking forward to tomorrow. Obviously, Paul knows how to motivate people. Thank you for that! Solving the challenge didn't take as much time as writing this blogpost ¯\_(ツ)_/¯