0

I am developing iOS with Swift 3.

I got country name string like "Japan", "Britain", "Spain", etc.

I am wondering what is the best way to generate NSLocale instance out from the country name?

I only found localizedString(forCountryCode:) in document, it means I have to manually parse country name to country code in my project like below:

switch countryName
{
     case "Spain":
          "ES"
}

Is there better way to generate locale from country name?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • 1
    Hm, maybe your usecase is different, but `NSLocalizedString()` uses the user's locale for you. And how would you handle countries like Switzerland where they have 3 official languages? – Wukerplank Sep 12 '17 at 09:40
  • 2
    @Wukerplank: Actually 4 languages: https://en.wikipedia.org/wiki/Languages_of_Switzerland. – Martin R Sep 12 '17 at 09:41
  • @MartinR Sorry, wasn't aware of that! I didn't mean to offend any Romansh speaking people! – Wukerplank Sep 12 '17 at 09:44
  • There are in fact (at least) 7 locales related to Switzerland: de_CH, rm_CH, wae_CH, fr_CH, gsw_CH, en_CH, it_CH – Martin R Sep 12 '17 at 09:50
  • 1
    @Wukerplank: There are even 2 for Austria: de_AT and en_AT. I wonder what the latter is – perhaps what Arnold Schwarzenegger speaks? – Martin R Sep 12 '17 at 09:54
  • Maybe you can tell us a little bit more WHY you need NSLocale by contry name...? – user8527410 Sep 12 '17 at 09:55
  • I have no control about the country name return, it is from 3rd party service, I am just developing client app. Otherwise, I would not use country name either. I just have no choice but live with the crappy country name. – Leem.fin Sep 12 '17 at 09:57
  • Hhow would you resolve the ambiguities described in above comments? Compare https://stackoverflow.com/questions/6556792/if-you-have-the-iso-country-code-us-fr-how-do-you-get-the-locale-code-lo which is about the same problem. – Martin R Sep 12 '17 at 10:03

1 Answers1

2

You can use CoreLocation framework. This code create a dictionary, where name of country is key, and ISO is value

    var dictionary = [String : String]()
    let arrayWithCodes = Locale.isoRegionCodes
    for code in arrayWithCodes {
        let description = Locale.current.localizedString(forRegionCode: code)
        if description != nil {
            dictionary[description!] = code
        }
    }
maxkoriakin
  • 337
  • 3
  • 7
  • That will give you a region code for the country, e.g. "CH" for Switzerland. How would you then choose the (NS)Locale ? – Martin R Sep 12 '17 at 13:19