(Solved) How to use Measurement.FormatStyle for generic over Measurement<UnitType: Dimension>?

See FormatStyle.measurement(): can only work for `UnitTemparature`, other type like `UnitMass` do not compile: Why overload not used? - #2 by jrose

This compiles and works:


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: Apple Developer Documentation

And two Measurement.FormatStyle.init's: 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: 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
        // 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 {
Terms of Service

Privacy Policy

Cookie Policy