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 insid
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)
Here is code for Swift 5.1 (well at least that works for me as a lot of functions has been renamed):
let array = NSLocale.isoCountryCodes.map
{
(code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
let currentLocaleID = NSLocale.current.identifier
return NSLocale(localeIdentifier: currentLocaleID).displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
array here is an [String]
Swift 4.2
let languageList = Locale.isoLanguageCodes.compactMap { Locale.current.localizedString(forLanguageCode: $0) }
let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
Here is @vedo27 's answer in Swift 3
let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
}
Swift 3 declared as a var
:
var countries: [String] {
let myLanguageId = "en" // in which language I want to show the list
return NSLocale.isoCountryCodes.map {
return NSLocale(localeIdentifier: myLanguageId).localizedString(forCountryCode: $0) ?? $0
}
}
Alternatively, you can have it in swift 4 and localized by the system language.
import Foundation
struct Country {
let name: String
let code: String
}
final class CountryHelper {
class func allCountries() -> [Country] {
var countries = [Country]()
for code in Locale.isoRegionCodes as [String] {
if let name = Locale.autoupdatingCurrent.localizedString(forRegionCode: code) {
countries.append(Country(name: name, code: code))
}
}
return countries
}
}