WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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")

3      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.