How do I get a list of countries in Swift ios?
Swift 4.2
let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: $0) }
let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
Swift You can easily retrieve countries name and their flags emoji.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var countriesData = [(name: String, flag: String)]()
for code in NSLocale.isoCountryCodes {
let flag = String.emojiFlag(for: code)
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
countriesData.append((name: name, flag: flag!))
}else{
//"Country not found for code: \(code)"
}
}
print(countriesData)
}
}
extension String {
static func emojiFlag(for countryCode: String) -> String! {
func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
return scalar.value >= 0x61 && scalar.value <= 0x7A
}
func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
precondition(isLowercaseASCIIScalar(scalar))
// 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
// 0x61 marks the start of the lowercase ASCII alphabet: 'a'
return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
}
let lowercasedCode = countryCode.lowercased()
guard lowercasedCode.count == 2 else { return nil }
guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }
let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: $0) })
return String(indicatorSymbols.map({ Character($0) }))
}
}
Result:
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)