Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Last active October 3, 2019 19:25
Show Gist options
  • Save SlaunchaMan/9e7adc3108a4c0f0522fd24e528ef3ef to your computer and use it in GitHub Desktop.
Save SlaunchaMan/9e7adc3108a4c0f0522fd24e528ef3ef to your computer and use it in GitHub Desktop.
Determining which Locales use miles for distance formatting.
import Foundation
import MapKit
extension Locale {
var usesMilesForDistanceFormatting: Bool {
guard usesMetricSystem else { return true }
let miles = Measurement(value: 42, unit: UnitLength.miles)
let kilometers = miles.converted(to: .kilometers)
let numberFormatter = NumberFormatter()
numberFormatter.locale = self
let formattedMiles = numberFormatter.string(
from: NSNumber(value: miles.value)
) ?? "42"
let formattedKilometers = numberFormatter.string(
from: NSNumber(value: kilometers.value)
) ?? "68"
let meters = miles.converted(to: .meters)
let distanceFormatter = MKDistanceFormatter()
distanceFormatter.locale = self
let formattedDistance = distanceFormatter.string(
fromDistance: meters.value
)
if formattedDistance.contains(formattedMiles) {
return true
} else if formattedDistance.contains(formattedKilometers) {
return false
} else {
assertionFailure("Could not determine if this locale uses miles.")
return false
}
}
}
@SlaunchaMan
Copy link
Author

This updated version includes locales that don’t format miles using the same numerals as English. The locales that use miles for distance formatting are:

Burmese (Myanmar [Burma]), Cornish (United Kingdom), Spanish (United States), Vai (Latin, Liberia), Cherokee (United States), Vai (Latin), English (Myanmar [Burma]), Cherokee, Lakota, Scottish Gaelic (United Kingdom), English (United States, Computer), English (Liberia), Kpelle (Liberia), English (United Kingdom), Hawaiian (United States), Vai (Liberia), Fulah (Liberia), Vai, English (United States), Vai, Hawaiian, Welsh (United Kingdom), Lakota (United States), Kpelle, Burmese, and English

The locales that return true for usesMetricSystem and also use miles for formatting are:

Cornish (United Kingdom), Scottish Gaelic (United Kingdom), English (United Kingdom), and Welsh (United Kingdom)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment