Swift Langauge version — Swift 5
Xcode: Version 12.2
This one is written when completing one of the challenge project of 100 days of SwiftUI by hackingwithswift. (https://www.hackingwithswift.com/100/swiftui/19)
Challenge was to create a simple length measurement app from scratch. User will input a length and choose input unit [meters, kilometers, feet, yards, or miles]. He will then choose output unit. App should show the converted unit in Text view.
Simple as it sounds! 👼
I am not going to talk about UI here, only the logical part.
Now logic is also simple, if user enter say 1 meter, and chooses Ft as output input, I simple need to multiply input number with 3.28 and show it as output. Or let Apple’s Measurement API do the job.
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 API provided by Apple to simplify conversions. You simply create an instance and use .converted method to convert it to any unit.
But problem is not the conversion but is to convert it in neater way.
Say user now chooses different input unit say yards, output unit as Ft, I need to convert yards to feet. And the combination goes on..
meter — Km
meter — Ft
meter — yards
meter — miles
This is just for meter , now similar combo goes next input unit.
How do I write logic here?
Should I put 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 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 make use of state variable outputUnit and we iterate through lengthUnits and provide Text View for each case.
Now Finally, output is calculated like below:
- input is the length entered by user in textField.
- inputUnit is unit selected by user for entered length.
- 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… ☺️