How do I retrieve the user's preferred unit from locale?
As far as I checked the documentations of Apple, I could not find any APIs to get preferred weight unit.
there sure are other weight / mass units out there
There are only three countries where the metric system is not used: the US, Liberia and Myanmar.
Testing with macOS 11.1 and iOS 14.4 Simulator, only one region "US" uses pounds.
extension Locale {
var measurementSystem: String {
(self as NSLocale).object(forKey: NSLocale.Key.measurementSystem) as! String
}
}
func formatWeight(for locale: Locale, weightInKgs: Double) - String {
let mformatter = MeasurementFormatter()
mformatter.locale = locale
mformatter.unitOptions = .naturalScale
mformatter.unitStyle = .medium
let weight = Measurement(value: weightInKgs, unit: UnitMass.kilograms)
return mformatter.string(from: weight)
}
let localeIds = ["en_US", "es_US", "en_GB", "en_LR", "my_MM", "ja_JP"]
for localId in localeIds {
let locale = Locale(identifier: localId)
print(locale, locale.measurementSystem)
print(locale.regionCode ?? "*region unknown*")
print("Uses Metric System: \(locale.usesMetricSystem)")
print(formatWeight(for: locale, weightInKgs: 100.1))
}
Output:
en_US (fixed) U.S.
US
Uses Metric System: false lb
es_US (fixed) U.S.
US
Uses Metric System: false lb
en_GB (fixed) U.K.
GB
Uses Metric System: true kg
en_LR (fixed) U.S.
LR
Uses Metric System: false kg
my_MM (fixed) U.S.
MM
Uses Metric System: false
၁၀၀.၁ kg
ja_JP (fixed) Metric
JP
Uses Metric System: true kg
(I'm not sure if kg is really preferred in daily life in the UK, but macOS/iOS uses kg for weight/mass when Locale set to en_GB.)
Seems using UnitMass.pounds is universal enough, practically.