Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of countries in Swift ios?

I've already seen two similar questions to mine, but the answers for those questions do not work for me. I have an old project with a list of countries manually typed out inside a set of square brackets.

I can easily use this in my pickerView but I'm wondering if there is a more efficient way to do this?

I will be using the list of countries in a UIPickerView.

like image 845
LondonGuy Avatar asked Jan 10 '15 11:01

LondonGuy


People also ask

How do you round down in swift?

Rounding Numbers in Swift By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.


2 Answers

You can get a list of countries using the NSLocale class's isoCountryCodes which returns an array of [String]. From there, you get the country name by using NSLocale's displayName(forKey:) method. It looks like this:

var countries: [String] = []  for code in NSLocale.isoCountryCodes  {     let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])     let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"     countries.append(name) }  print(countries) 
like image 59
Ian Avatar answered Nov 16 '22 03:11

Ian


SWIFT 3 and 4

var countries: [String] = []  for code in NSLocale.isoCountryCodes as [String] {     let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])     let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"     countries.append(name) }  print(countries) 
like image 24
Oscar Falmer Avatar answered Nov 16 '22 02:11

Oscar Falmer