GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.