TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Challenge 1 day 19 solution I know I can improve it but how?

Forums > 100 Days of SwiftUI

@ob29-  


import SwiftUI

struct ContentView: View {

    @State private var lengthIn = 0.0
    @State private var chosenIn = "Meter"
    @State private var chosenOut = "Kilometer"
    let measurements = ["Kilometer", "Meter", "Centimeter"]

    var inputLengthToCm: Double {
        var lengthToCm = lengthIn
        if chosenIn == "Meter"{
            lengthToCm *= 100
        } else if chosenIn == "Kilometer" {
            lengthToCm *= 100_000
        } else {
            return lengthToCm
        }
        return lengthToCm
    }

    var outputLengthUnit: Double{
        var finalLength = inputLengthToCm

        if chosenOut == "Meter" {
            finalLength = inputLengthToCm / 100
        } else if chosenOut == "Kilometer" {
            finalLength = inputLengthToCm / 100_000
        } else {
            finalLength = inputLengthToCm
        }
        return finalLength
    }

    @FocusState private var outputLengthUnitFocused: Bool

    var body: some View {
        NavigationStack{
            Form{
                //Text Input
                Section{
                    TextField("Length In", value: $lengthIn, format: .number)
                }.keyboardType(.decimalPad)
                    .focused($outputLengthUnitFocused)

                Section("Input Measurement"){
                    Picker("Input Unit", selection: $chosenIn){
                        ForEach(measurements, id: \.self){
                            Text($0)
                        }
                    }.pickerStyle(.segmented)
                }

                Section("Output Unit"){Picker("Output Unit", selection: $chosenOut){
                    ForEach(measurements, id: \.self){
                        Text($0)
                    }
                }.pickerStyle(.segmented)}

                Section("Output Length in \(chosenOut)"){Text(outputLengthUnit, format: .number)}

            }.navigationTitle("Measurement Converter")
                .navigationBarTitleDisplayMode(.inline)
                .toolbar{ if outputLengthUnitFocused {
                    Button("Done"){
                        outputLengthUnitFocused = false
                    }
                }
                }
        }
    }
}

So i have completed challenge 1 however I'm wondering how I could make my code more streamline. The aim is to convert any input into Centimeter first before then converting the cm to KM or M

3      

You can look up using Dimension, Measurement, Units and .converted - here is an example for temperature

3      

@Tommy  

import SwiftUI

struct ContentView: View {
    @State private var value = 42.0
    @State private var type = ConversionType.temperature

    @State private var tempForm = UnitTemperature.celsius
    @State private var tempTo = UnitTemperature.fahrenheit

    @State private var lengthForm = UnitLength.meters
    @State private var lengthTo = UnitLength.kilometers

    @State private var timeForm = UnitDuration.nanoseconds
    @State private var timeTo = UnitDuration.seconds

    @FocusState private var isFocused

    private enum ConversionType: String, CaseIterable {
        case temperature = "🌡️"
        case length = "📏"
        case time = "⏱️"
    }

    private var result: String {
        switch type {
        case .temperature:
            Measurement(value: value, unit: tempForm).converted(to: tempTo).description
        case .length:
            Measurement(value: value, unit: lengthForm).converted(to: lengthTo).description
        case .time:
            Measurement(value: value, unit: timeForm).converted(to: timeTo).description
        }
    }

    var body: some View {
        Form {
            Section("Conversion Value") {
                TextField("Value", value: $value, format: .number)
                    .keyboardType(.decimalPad)
                    .focused($isFocused)
            }

            Section("What do you want to convert?") {
                Picker("", selection: $type) {
                    ForEach(ConversionType.allCases, id: \.self) {
                        Text($0.rawValue)
                            .font(.largeTitle)
                    }
                }
                .pickerStyle(.segmented)
            }

            Section("From") {
                switch type {
                case .temperature:
                    Picker("", selection: $tempForm) {
                        ForEach(UnitTemperature.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                case .length:
                    Picker("", selection: $lengthForm) {
                        ForEach(UnitLength.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                case .time:
                    Picker("", selection: $timeForm) {
                        ForEach(UnitDuration.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                }
            }

            Section(header: Text("To")) {
                switch type {
                case .temperature:
                    Picker("", selection: $tempTo) {
                        ForEach(UnitTemperature.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                case .length:
                    Picker("", selection: $lengthTo) {
                        ForEach(UnitLength.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                case .time:
                    Picker("", selection: $timeTo) {
                        ForEach(UnitDuration.cases, id: \.self) {
                            Text($0.symbol)
                        }
                    }
                    .pickerStyle(.segmented)
                }
            }

            Section("Result") {
                Text(result)
            }
        }
    }
}

extension UnitTemperature {
    public static var cases: [UnitTemperature] {
        return [.celsius, .fahrenheit, .kelvin]
    }
}

extension UnitLength {
    public static var cases: [UnitLength] {
        return [.meters, .kilometers, .feet, .yards, .miles]
    }
}

extension UnitDuration {
    public static var cases: [UnitDuration] {
        return [.nanoseconds, .seconds, .minutes, .hours]
    }
}

#Preview {
    ContentView()
}

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.