Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Display the user's language in SwiftUI.
Display the user's language in SwiftUI.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.