Generic input field for any numerical value with the associated unit

Target: Generic input field for any numerical value with the associated unit. The metadata for this input field is stored in a database and includes:

  • What the value should represent (text).
  • Which unit applies to it (text)

For this I try to write the following function:

 func getMeasurment(value: Double, unit: String) -> Measurement<Unit> {
        switch(unit) {

        case "UnitArea.squareKilometers":

            let result = Measurement(value: value, unit: UnitArea.squareKilometers)

            return result

        case "...":

                ....

        }

Of course I get a compiler error, is there a possible solution for this task?

Please excuse my question, but I am absolute beginner in Swift ...

   

Replace with UnitArea:

func getMeasurment(value: Double, unit: String) -> Measurement<UnitArea> { }

Thank you for your feedback. Unfortunately, this does not solve my problem. The function is supposed to be applicable for all possible (like UnitArea, UnitAcceleration, UnitAngle, ...). I wrote the following function which returns me the desired result as string.

func showMeasurement(value: Double, unit: String, symbol: Bool) -> String {

        switch(unit) {
            //MARK: Aceleration

        case "UnitAcceleration.metersPerSecondSquared":

            let newValue = Measurement(value: value, unit: UnitAcceleration.metersPerSecondSquared)

            if symbol {

                return newValue.unit.symbol

            } else {

                return newValue.formatted(.measurement(width: .narrow, usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2))))

            }



        case "UnitAcceleration.UnitAcceleration":

            let newValue = Measurement(value: value, unit: UnitAcceleration.baseUnit())

            if symbol {

                return newValue.unit.symbol

            } else {

                return newValue.formatted(.measurement(width: .narrow, usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2))))

            }
  ....

But later I will also need the corresponding Measurment to be able to calculate with the values.

Generic input field for any numerical value with the associated unit
 
 
Q