This compiles and works:
aMeasurement.formatted()
This do not:
aMeasurement.formatted(.measurement(usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2))))
Compile error:
Instance method 'formatted' requires the types 'Measurement<UnitTemperature>.FormatStyle.FormatInput' (aka 'Measurement<UnitTemperature>') and 'Measurement<UnitType>' be equivalent
The old MeasurementFormatter
can work with generic over Dimension
.
Don't know how to fix this because there are two different static .measurement()
's: FormatStyle | Apple Developer Documentation
And two Measurement.FormatStyle.init
's: Measurement.FormatStyle | Apple Developer Documentation
One for UnitTemperature
and the other for the other Unit
types. The special case for UnitTemperature
is the problem: how to get around this?
The example here: formatted(_:) | Apple Developer Documentation only show formatting Measurement<UnitTemperature>
, not generic for all Dimension
types.
My test:
import SwiftUI
// Want generic over `Dimension`
struct GenericOverDimensionGizmo<UnitType: Dimension>: View {
@Binding var value: Measurement<UnitType>
var body: some View {
// this works
Text(value.formatted())
// Need to configure the FormatStyle, but ...
// the following do not compile
// Compile error: Instance method 'formatted' requires the types 'Measurement<UnitTemperature>.FormatStyle.FormatInput' (aka 'Measurement<UnitTemperature>') and 'Measurement<UnitType>' be equivalent
Text(value.formatted(.measurement(usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2))))) // ❌💣
// Compile error: Cannot convert value of type 'Measurement<UnitType>' to expected argument type 'Measurement<UnitTemperature>.FormatStyle.FormatInput' (aka 'Measurement<UnitTemperature>')
Text(value, format: .measurement(usage: .asProvided, numberFormatStyle: .number.precision(.fractionLength(2)))) // ❌💣
}
}
struct GenericOverDimensionGizmoDemo: View {
@State private var weight = Measurement(value: 26.7, unit: UnitMass.kilograms)
var body: some View {
GenericOverDimensionGizmo(value: $weight)
}
}
struct GenericOverDimensionGizmoDemo_Previews: PreviewProvider {
static var previews: some View {
GenericOverDimensionGizmoDemo()
}
}