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

1      

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

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

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.