Hi everyone! I have a pitch to make the Locale
API easier to use by introducing Locale.preferredLocales
.
Introduction
Add Locale.preferredLocales
as an alternative to Locale.preferredLanguages
that returns [Locale]
instead of [String]
.
Motivation
Currently, Locale.preferredLanguages
is the only way to retrieve the list of languages that the user has specified in Language & Region settings. This follows its predecessor +[NSLocale preferredLanguages]
and returns an array of String
s instead of Locale
s. Processing and manipulating strings is complex and errorprone for clients.
This proposal introduces Locale.preferredLocales
as a way to retrieve the same information, but in the form of an array of Locale
s which will allow clients to use the information more easily and with fewer errors, specifically when used to customize the presentation of data within their apps such that content in the user’s preferred languages is more prominent.
Proposed solution
We propose adding preferredLocales
as a static variable on Locale
, similarly to preferredLanguages
. One of the primary use cases is to allow apps to build language selection menus in which the user’s preferred locales are bubbled up to the top. This can be achieved with the proposed preferredLocales
API as follows:
// When building a language selection menu, `matchedLocales` would be shown at the top, and `otherLocales` would be shown below, with a visual divider.
var matchedLocales = []
var otherLocales = []
let availableLocales = // ... array of Locale objects ...
for locale in availableLocales {
var foundMatch = false
for preferredLocale in preferredLocales {
if locale.language.isEquivalent(to: preferredLocale.language) {
matchedLocales.append(locale)
foundMatch = true
break
}
}
if !foundMatch {
otherLocales.append(locale)
}
}
Please take a look at the full proposal in the swift-foundation repo PR.