Home > Net >  SwiftUI BaseUnit implementation custom measurement
SwiftUI BaseUnit implementation custom measurement

Time:11-30

For calculating the pressure drop in a pipe, I use a pipe class with a flow parameter. I would like to implement a custom measurement for a flow rate, but I get an "exception 'NSInvalidArgumentException', reason: '*** You must override baseUnit in your class ... to define its base unit.'" error.

My code for the flow unit dimension is:

class UnitFlow: Dimension {
    static let cubicMeterPerSecond = UnitFlow(symbol: "m3/s", converter: UnitConverterLinear(coefficient: 1.0))
    static let cubicMeterPerMinute = UnitFlow(symbol: "m3/min", converter: UnitConverterLinear(coefficient: 60.0))
    static let cubicMeterPerHour = UnitFlow(symbol: "m3/h", converter: 
    //et cetera
          
    static let baseUnit = UnitFlow(symbol: "m3/s", converter: UnitConverterLinear(coefficient: 1.0))
}

Where it goes wrong is in this line:

Text("\(pipe.flow.converted(to: UnitFlow.cubicMeterPerMinute).value)")

Any thoughts?

CodePudding user response:

As the error suggests, you need to override baseUnit. However, this is a method - not a variable.

Remove your current baseUnit, and replace it with the following:

class UnitFlow: Dimension {
    /* ... */

    override class func baseUnit() -> Self {
        Self(symbol: "m3/s")
    }
}
  • Related