— Swift, Locale, UserDefaults — 1 min read
In iOS app development, it's often necessary to check the language of the device in order to provide a localized user experience. In this article, we will show you how to check if a device's language is set to Japanese in Swift.
There are two methods for determining the device's language in Swift:
The UserDefaults class provides access to the user's default settings and preferences. In this case, we can access the AppleLanguages key in UserDefaults to determine the device's language. Here's how to do it:
1let language = UserDefaults.standard.object(forKey: "AppleLanguages") as? [String]2if let language = language, language.first == "ja" {3 print("Device language is Japanese")4} else {5 print("Device language is not Japanese")6}
Another way to determine the device's language is to use the Locale class. Here's how to do it:
1let locale = Locale.current2if locale.languageCode == "ja" {3 print("Device language is Japanese")4} else {5 print("Device language is not Japanese")6}
That's it! With these two methods, you can easily check the device's language in Swift and provide a localized user experience.