Olter Olter - 10 months ago 78
Objective-C Question

Remove region code from NSLocale.preferredLanguages array

After updating my Mac to OSX Sierra, I have noticed, that the

array is now in different format (See quick explanation here)

Also, same thing happens for IOS9, I suppose.

So, in short, previously we had language format "en", "fr", "ru", e.t.c

Now, we have format "en-US", "en-RU", "fr-US" e.t.c.

In my application, some controls' coordinates were related to the locale. Now, because of the different format, they are all wrong. I was thinking about best way to fix this and to remain support for older versions.

So, my question is:

Is there any way of receiving the language code without region code only? The quick and dirty solution would be to read first two symbols from this string. Is there a more elegant one?

P.S. Can someone please explain Apple's logic to me. I mean, why they have decided, that best option would be to change the existing object format(breaking the backwards compatibility) instead of adding additional field to NSLocale?

Answer Source

You can use substringToIndex as follows:

let str = "en-US"

if let indexOfDash = str.characters.indexOf("-") {
    let langCode = str.substringToIndex(indexOfDash)

This way should the language code be longer than 2 chars for whatever reason, you don't get caught out.