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

SOLVED: [Challenge Day 1] Can't figure out what's wrong

Forums > 100 Days of SwiftUI

@GutoP  

Hi Guys, hope you are all fine.

I've been trying to figure out what is wrong with my solution for the first Challenge for the past hour and I can't seem to find it. What I realized so far:

  1. Changing the input unit makes result change
  2. Changing the output unit doesn't make a difference
  3. When you change the type of conversion, the output defaults to the last option of output, no matter what is selected.

If anyone can take a look, I'd be very greatuful! Thanks


import SwiftUI

struct ContentView: View {
    @State private var input : Double = 32.0

    @State private var unitInput: Dimension = UnitTemperature.celsius

    @State private var unitOutput: Dimension = UnitTemperature.celsius
    var converterType = ["Temperature", "Distance", "Time", "Volume"]

    @State var selectedUnit = 0

   var unitType = [
        [UnitTemperature.celsius, UnitTemperature.fahrenheit, UnitTemperature.kelvin],
        [UnitLength.meters, UnitLength.kilometers,
         UnitLength.inches, UnitLength.feet, UnitLength.yards, UnitLength.miles],
        [UnitDuration.hours, UnitDuration.minutes, UnitDuration.seconds],
        [UnitVolume.milliliters, UnitVolume.liters, UnitVolume.cups, UnitVolume.pints, UnitVolume.gallons]
    ]

    var result: String {
        let inputValue = Measurement(value: input, unit: unitInput)
        let outputValue = inputValue.converted(to: unitOutput)

        return MeasurementFormatter().string(from: outputValue)

        }

    var body: some View {
        NavigationView{
            Form{
                //section to choose what to convert
                Section{
                    Picker("Conversion Type",  selection: $selectedUnit) {
                        ForEach(0..<converterType.count){
                            Text(converterType[$0])
                        }
                    } .pickerStyle(.segmented)
                } header: {
                    Text("Choose what to convert")
                }

                //section to choose what the input unit is
                Section{
                 TextField("Value", value: $input, format: .number)
                     .keyboardType(.decimalPad)
                Picker("Input Unit", selection: $unitInput) {
                    ForEach(unitType[selectedUnit], id: \.self){
                        Text(MeasurementFormatter().string(from: $0).capitalized)
                    }
                } .pickerStyle(.segmented)
                } header: {
                 Text("Value to convert")
                }

                //section to show converted value
                Section{
                Picker("Output Unit", selection: $unitOutput) {
                    ForEach(unitType[selectedUnit], id: \.self){
                        Text(MeasurementFormatter().string(from: $0).capitalized)
                    }
                } .pickerStyle(.segmented)
                 Text(result)

                } header: {
                 Text("Converted Value")
                }

            }
            .navigationTitle("Converter")
            .onChange(of: selectedUnit) { newSelection in
                let units = unitType[newSelection]
                unitInput = units[0]
                unitOutput = units[1]
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

You may have a layer of added complexity in your result computed property?

outputValue is a Measurement struct. If you peek at Apple's documentation, you'll see that every Measurement struct has a formatted() method that returns a string.

Instead of shoving your outputValue into a MeasurementFormatter(), try using the Measurement's formatted() func.

var result: String {
     let inputValue  = Measurement(value: input, unit: unitInput)
     let outputValue = inputValue.converted(to: unitOutput)
     // return MeasurementFormatter().string(from: outputValue)
     return outputValue.formatted()  // TRY this instead. Use the built in formatted() function.
}

Let us know how you solve this!

4      

@GutoP  

Hi @Obelix, as always, you saved the day! I am still not sure why the way i wrote the return function would cause all this trouble, but i promise to take a look at the documentation and try to learn more.

Thank you very much for your time!!

4      

Hi @GutoP

I know you marked as solved. However would like to piont out something, in your code you make number of instances of MeasurementFormatter() which can effect proformance.

If you make it once and then reuse it, it would of solved the problem eg

let formatter: MeasurementFormatter

init() {
    formatter = MeasurementFormatter()
    formatter.unitOptions = .providedUnit
    formatter.unitStyle = .short
}

and then replace everywhere you used MeasurementFormatter() with formatter

var result: String {
  let inputValue = Measurement(value: input, unit: unitInput)
  let outputValue = inputValue.converted(to: unitOutput)

  return MeasurementFormatter().string(from: outputValue)

}
Text(formatter.string(from: $0).capitalized)

but glad that you above solution worked.

3      

Hi guys,

I am getting this error on the closing bracket of the MeasurementFormatter init - Return from initializer without initializing all stored properties

Any help will be amazing

Regards

Paul

import SwiftUI

struct ContentView: View {

 @State public var info: UnitInfo

@State private var inputUnit: Dimension = UnitTemperature.celsius
@State private var outputUnit: Dimension = UnitTemperature.fahrenheit
@State private var input = 100.0
@State private var selectedUnits = 0
@FocusState private var keyboardIsFocused: Bool

let formatter: MeasurementFormatter

init () {
    formatter = MeasurementFormatter()
    formatter.unitOptions = .providedUnit
    formatter.unitStyle = .short
}

let conversions = ["Unit for Measure for Acceleration", "Unit for Measure for Planar Angle and Rotation", "Unit of Measure of Area", "Unit of Measure for Concentration of Mass", "Unit of Measure of Dispersion", "Unit of measure for duration of Time","Unit of Measure for Electric Charge", "Unit of Measure of Electric Current", "Unit of Measure for Electric Potential Difference","Unit of Measure for Electric Resistance","Unit of Measure for Energy","Unit of Measure for Frequency","Unit of Measure for Fuel Efficiency","Unit of Measure for Illuminance", "Unit of Measure for  Quantities of Information","Unit of Measure of Lenght", "Measure of Mass", "Measure of Power", "Unit of Measure for Pressure", "Unit for Measure of Speed", "Unit of Measure for Temperature", "Unit of Measure for Volume"]

let unitTypes = [
    [UnitAcceleration.metersPerSecondSquared, UnitAcceleration.gravity],
    [UnitAngle.degrees, UnitAngle.arcMinutes, UnitAngle.arcSeconds, UnitAngle.radians, UnitAngle.gradians, UnitAngle.revolutions],
    [UnitArea.squareMegameters, UnitArea.squareKilometers, UnitArea.squareCentimeters, UnitArea.squareMillimeters, UnitArea.squareMicrometers, UnitArea.squareNanometers, UnitArea.squareInches, UnitArea.squareFeet, UnitArea.squareYards, UnitArea.squareMiles, UnitArea.acres, UnitArea.ares, UnitArea.hectares],
    [UnitConcentrationMass.gramsPerLiter, UnitConcentrationMass.milligramsPerDeciliter],
    [UnitDispersion.partsPerMillion],
    [UnitDuration.seconds, UnitDuration.minutes, UnitDuration.hours],
    [UnitElectricCharge.coulombs, UnitElectricCharge.megaampereHours, UnitElectricCharge.kiloampereHours, UnitElectricCharge.ampereHours, UnitElectricCharge.milliampereHours, UnitElectricCharge.microampereHours],
    [UnitElectricCurrent.megaamperes, UnitElectricCurrent.kiloamperes, UnitElectricCurrent.amperes, UnitElectricCurrent.milliamperes, UnitElectricCurrent.microamperes],
    [UnitElectricPotentialDifference.megavolts, UnitElectricPotentialDifference.kilovolts, UnitElectricPotentialDifference.volts, UnitElectricPotentialDifference.millivolts, UnitElectricPotentialDifference.microvolts],
    [UnitElectricResistance.megaohms, UnitElectricResistance.kiloohms, UnitElectricResistance.ohms, UnitElectricResistance.milliohms, UnitElectricResistance.microohms],
    [UnitEnergy.kilojoules, UnitEnergy.joules, UnitEnergy.kilojoules, UnitEnergy.calories, UnitEnergy.kilowattHours],
    [UnitFrequency.terahertz, UnitFrequency.gigahertz, UnitFrequency.megahertz, UnitFrequency.kilohertz, UnitFrequency.hertz, UnitFrequency.millihertz, UnitFrequency.microhertz, UnitFrequency.nanohertz],
    [UnitFuelEfficiency.litersPer100Kilometers, UnitFuelEfficiency.milesPerGallon, UnitFuelEfficiency.milesPerImperialGallon],
    [UnitIlluminance.lux],
    [UnitInformationStorage.kilobits, UnitInformationStorage.megabits, UnitInformationStorage.gigabits, UnitInformationStorage.terabits, UnitInformationStorage.petabits, UnitInformationStorage.exabits, UnitInformationStorage.zettabits, UnitInformationStorage.yottabits, UnitInformationStorage.kibibits, UnitInformationStorage.mebibits, UnitInformationStorage.gibibits, UnitInformationStorage.tebibits, UnitInformationStorage.pebibits, UnitInformationStorage.exbibits, UnitInformationStorage.zebibits, UnitInformationStorage.yobibits ],
    [UnitLength.meters, UnitLength.miles, UnitLength.feet, UnitLength.yards, UnitLength.kilometers],
    [UnitMass.grams, UnitMass.kilograms, UnitMass.ounces, UnitMass.pounds, UnitMass.stones],
    [UnitPower.terawatts, UnitPower.gigawatts, UnitPower.megawatts, UnitPower.kilowatts, UnitPower.watts, UnitPower.milliwatts, UnitPower.microwatts, UnitPower.nanowatts, UnitPower.picowatts, UnitPower.femtowatts, UnitPower.horsepower],
    [UnitPressure.newtonsPerMetersSquared, UnitPressure.gigapascals, UnitPressure.megapascals, UnitPressure.kilopascals, UnitPressure.hectopascals, UnitPressure.inchesOfMercury, UnitPressure.bars, UnitPressure.millibars, UnitPressure.millimetersOfMercury, UnitPressure.poundsForcePerSquareInch],
    [UnitSpeed.metersPerSecond, UnitSpeed.kilometersPerHour, UnitSpeed.milesPerHour, UnitSpeed.knots],
    [UnitTemperature.celsius, UnitTemperature.fahrenheit, UnitTemperature.kelvin],
    [UnitVolume.megaliters, UnitVolume.kiloliters, UnitVolume.liters, UnitVolume.deciliters, UnitVolume.centiliters, UnitVolume.milliliters, UnitVolume.cubicKilometers, UnitVolume.cubicMeters, UnitVolume.cubicDecimeters, UnitVolume.cubicMillimeters, UnitVolume.cubicInches, UnitVolume.cubicFeet, UnitVolume.cubicYards, UnitVolume.cubicMiles, UnitVolume.acreFeet, UnitVolume.bushels, UnitVolume.teaspoons, UnitVolume.tablespoons, UnitVolume.fluidOunces, UnitVolume.cups, UnitVolume.pints, UnitVolume.quarts, UnitVolume.gallons, UnitVolume.imperialTeaspoons, UnitVolume.imperialTablespoons, UnitVolume.imperialFluidOunces, UnitVolume.imperialPints, UnitVolume.imperialQuarts, UnitVolume.imperialGallons,UnitVolume.metricCups]
]

var result: String {
    let inputMeasurement = Measurement(value: input, unit: inputUnit)
    let outputMeasurement = inputMeasurement.converted(to: outputUnit)
    return formatter.string(from: outputMeasurement)

}

var body: some View {
    NavigationView {
        Form {
            Section{
                TextField("Amount", value: $input, format: .number)
                    .keyboardType(.decimalPad)
                    .focused($keyboardIsFocused)
            } header: {
                Text("Amount to convert")
            }
            Picker("Conversion", selection: $selectedUnits){
                ForEach(0..<conversions.count) {
                    Text(conversions[$0])
                }
            }
            Picker("Convert From", selection: $inputUnit) {
                ForEach(unitTypes[selectedUnits], id: \.self) {
                    Text(formatter.string(from: $0).capitalized)
                }
            }
            Picker("Convert To", selection: $outputUnit) {
                ForEach(unitTypes[selectedUnits], id: \.self) {
                    Text(formatter.string(from: $0).capitalized)
                }
            }
            Section {
                Text(result)
                    .foregroundColor(.red)
            } header: {
                Text("Results")
            }
            Section {
                TextField("About", text: ($info.detail))
            } header: {
                Text("About unit of")
            }

            }
            .navigationTitle("Converter")
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("Done") {
                        keyboardIsFocused = false
                    }
                }
            }
            .onChange(of: selectedUnits) { newSelection in
                let units = unitTypes[newSelection]
                inputUnit = units[0]
                outputUnit = units[1]
            }
        }

    }

}

struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }

3      

@paulidupreez

Please Delete

Please delete your entry above. Your question is not related to the original question. Plus, you posted this question as its own topic and it's been answered.

Thanks!

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.