How do I get a list of countries in Swift ios?
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)
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)
Swift 4.2
let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: $0) }let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }