SwiftUI - Length Measurement App

Hithakshi Kulal
3 min readMar 21, 2021

--

SwiftUI
Swift Langauge version — Swift 5
Xcode: Version 12.2

Photo by William Warby on Unsplash

This was written on completion of one of SwiftUI’s 100-day challenge projects by hackingwithswift.

(https://www.hackingwithswift.com/100/swiftui/19)

The challenge consisted of creating a simple length measurement application from scratch. The user will enter a length and choose the input unit [metres, kilometres, feet, meters or miles]. He will then pick the output unit. The app should display the converted unit in the text view.

Simple as it sounds! 👼

I am not going to talk about UI here, only the logical part.

Running on iPhone 8 (14.2) simulator

Now the logic is quite simple. if the user enters say 1 meter, and selects Ft as the output and input unit, I just need to multiply the input number by 3.28 and show it as the output. Or let Apple’s measurement APIs do the work.
I need to maintain a 3 state variables:
1. Selected input unit
2. Selected output unit
3. Length (input entered by user in TextField)

Measurement is an Apple-delivered API for simplifying conversions. You just create an instance and use the .converted method to convert it to some unit.

But the problem is not the conversion, but to convert it in a clearer way.

If the user now chooses different input units say yards, output unit as ft, I need to convert yards to feet. And the combo continues.

meter — Km
meter — Ft
meter — yards
meter — miles

This is just for meter , now similar combo goes next input unit.
How do you put logic here?
Should I put the switch case to compute for each combo ? That’s opposite of neat code. 😣

How can I make use of Apple’s Measurement API and write logic to return the converted measurement length with lesser code? 😐

We have our dear friend for this problem. . Enums 😉

We know for a fact that we have to provide set of values for Segmented Control. i.e [meters, kilometers, feet, yards, or miles]. Why don’t we maintain enum for this case and let each case provide their measurement type.

I would then create Picker like this. Picker makes use of state variable outputUnit and we iterate through lengthUnits and provide Text View for each case.

Now Finally, output is calculated like below:

  1. input is the length entered by user in textField.
  2. inputUnit is unit selected by user for entered length.
  3. outputUnit is unit selected by user for conversion.

Since they are of Unit type, I can easily take their UnitLength and apply it on Measurement API to convert the value.

No switch cases, no if else. Simple logic!

Interested to check full code? Check this github link LengthConversion. 👼

Thank you for reading… ☺️

--

--

Hithakshi Kulal
Hithakshi Kulal

Written by Hithakshi Kulal

iOS developer at Robosoft Technologies

Responses (1)