NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

1st Challenge done, with round about solution lol

Forums > 100 Days of SwiftUI

Hi guys, Just finished my solution to the first challenge. I didnt read about the converter section of the page and just barrelled through creating a solution. it works but would love some insight to a better solution.

@State var value1 = ""
    @State var distance1 = 2
    @State var distance2 = 2

    let distances = ["Meters", "Km", "Feet", "Yards", "Miles"]
    let milesLength = ["0.00062137", "0.621371", "0.0001893938807992424", "0.00056818164239772720337", "1"]

    var finalValue: Double {
        let convert = Double(value1) ?? 0
        let distanceToValue = Double(milesLength[distance2]) ?? 2
        let distanceFromValue = Double(milesLength[distance1]) ?? 2

        let milesValue = convert * distanceFromValue
        let value = milesValue / distanceToValue

        return value
    }

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Measurement")) {
                    TextField("Measurement length", text: $value1)
                        .keyboardType(/*@START_MENU_TOKEN@*/.decimalPad/*@END_MENU_TOKEN@*/)
                }
                Section(header: Text("First measurement type to convert")) {
                    Picker("First measurement type to convert", selection: $distance1) {
                        ForEach(0 ..< distances.count) {
                            Text("\(self.distances[$0])")
                        }
                    }.pickerStyle(SegmentedPickerStyle())
                }
                Section(header: Text("Measurement type to convert too")) {
                    Picker("First measurement type to convert", selection: $distance2) {
                        ForEach(0 ..< distances.count) {
                            Text("\(self.distances[$0])")
                        }
                    }.pickerStyle(SegmentedPickerStyle())
                }
                Text("The conversion is \(finalValue, specifier: "%.2f") \(distances[distance2])")
            }.navigationTitle("Distance Converter")

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.