-2

I would like implement a native iOS country picker in swift 4. Currently I have a table which contain the countries code:

var countriesCodes = NSLocale.isoCountryCodes as [String]

I implement the delegate, and I have a problem in the data source. How to convert each country code in country name?

clementb49
  • 1
  • 2
  • 5

1 Answers1

4

You can convert each country code key into its localised display name using the following function provided in Foundation (documentation here):

Locale.current.localizedString(forRegionCode:)
// "NZ" -> "New Zealand"

You can convert your country code array to display names using flatMap:

let countryNames = countriesCodes.flatMap(
    Locale.current.localizedString(forRegionCode:))

Although you may wish to make a tuple pair of the ISO country code and its localised display name together, which would be much more useful:

let countryCodesAndNames = countriesCodes.flatMap { code in
    Locale.current.localizedString(forRegionCode: code).map { (code, $0) }
}
// countryCodesAndNames is type [(String, String)]
// which is (ISO code, displayName)
// eg.
print(countryCodesAndNames[0])
// prints ("AC", "Ascension Island")
Jake
  • 545
  • 2
  • 6