UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.