I was experimenting in a playground with the specifying the kind of measurement with MeasurementUnit and then formatting it with the new foundation formatters, specifically MeasurementFormatter.
The particular example I was using is a UnitDuration
, exploring the various options and outputs.
let times = [1,10,100,1000,10103,2354,83674,182549].map {
Measurement<UnitDuration>(value: $0, unit: .microseconds)
}
print("unitStyle: .medium, unitOptions: .providedUnit")
f.unitOptions = .providedUnit
f.unitStyle = .medium
for t in times {
print(f.string(from: t))
}
What I gathered from this exploration is that the unit you use when you create a Measurement<UnitDuration>
is stashed within it - in this case I created them with microseconds
.
What I'd like to do have a uniform scale for the times I'm printing that more aligned with the size based on the values. For example, if all my examples are recorded in microseconds, but more usefully represent milliseconds - is there a way to deal with this just in the formatting itself?
I tried updating the unit representation to transform the MeasurementUnit<Duration>
instances, but the unit property is a constant: Cannot assign to property: 'unit' is a 'let' constant
. I did find the convert(to:)
that would let me transform to another specific unit.
Is there, by chance, any way to pass in the unit to use directly to a MeasurementFormatter instance, or do I need to back out and transform the various instances to get to a specific unit?
Likewise, are there any built-in methods to MeasurementUnit that align the SI units chosen to the scale of the data being used as a value? Or is that something I'd need to create a heuristic/algorithm to and do and apply it myself when I wanted that result?