user3224534 user3224534 - 1 year ago 98
Swift Question

check language in iOS app

Task is : I have got two UIImageViews, and I want present ImageView1 if system language is Ukrainian, and if it is not Ukrainian(English/Polish etc) I want present ImageView2.

I tried :


but this code gives only list of available languages. I also tried

var language: AnyObject? = NSLocale.preferredLanguages().first

but how can I compare this variable with English or Ukrainian language?

Answer Source

You can take the language code like this

let preferredLanguage = NSLocale.preferredLanguages()[0] as String

And then you need to compare it with code string

if preferredLanguage == "en" {
    println("this is English")
} else if preferredLanguage == "uk" {
    println("this is Ukrainian")

You can find codes here


Considering what holroy mentioned about safe unwrapping, you can wrap previous written code with this conditional unwrapping:

if let preferredLanguage = NSLocale.preferredLanguages()[0] as String? {

An example to check if French ...

func isFrench()->Bool
    if let pref = NSLocale.preferredLanguages()[0] as String?
        // consider, "fr-CA", "fr-FR", "fr-CH" et cetera
        if ( pref.containsWord("fr" ) ) { return true }
    return false

// (generally very useful extension...)
public extension String
    func containsWord(w:String)->Bool
        if (self.rangeOfString(w) == nil ) { return false }
        else { return true }

You could similarly check for "en" etc., pref.containsWord("en")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download