Display the User's Language in SwiftUI
Written by Team Kodeco
Creating an inclusive and accessible app involves considering users from all around the globe. This approach entails respecting and acknowledging users’ language preferences. This chapter will demonstrate how to display the user’s preferred language in a SwiftUI app.
In SwiftUI, the Foundation framework’s Locale
class provides access to the user’s language preference. This class can be used to retrieve the language preference and present it within a SwiftUI view.
Below is a complete example of how this can be achieved:
struct ContentView: View {
var userPreferredLanguage: String {
return Locale.preferredLanguages.first ?? "Language preference not found"
}
var userPrimaryLanguage: String {
let locale = Locale.autoupdatingCurrent
guard let primaryLanguage = locale.language.languageCode?.identifier else { return "Language code not found" }
return NSLocale.current.localizedString(forLanguageCode: primaryLanguage) ?? "Language not found"
}
var body: some View {
VStack {
Text("Your preferred language is \(userPreferredLanguage)")
Text("Your primary language is \(userPrimaryLanguage)")
}.padding()
}
}
If your language is set to English, here’s what your preview will look like:
This code defines a SwiftUI view, ContentView
, displaying the user’s preferred and primary languages. The userPreferredLanguage
computed property fetches the first preferred language in the Locale.preferredLanguages
array. If no preferred languages are found, it defaults to the string “Language preference not found”.
The userPrimaryLanguage
computed property retrieves the primary language code from Locale.autoupdatingCurrent
. If no primary language is found, it defaults to the string “Language code not found”. The language code is then localized to the language’s full name using NSLocale.current.localizedString(forLanguageCode:)
.
Creating an inclusive and accessible app starts with respecting users’ language preferences. Check out other chapters in this section to learn more techniques for internationalizing and localizing your apps.