Swift - Get list of countries

后端 未结 3 1583
抹茶落季
抹茶落季 2021-02-06 13:55

How can I get an array with all countries names in Swift? I\'ve tried to convert the code I had in Objective-C, which was this:

if (!pickerCountriesIsShown) {
           


        
3条回答
  •  情话喂你
    2021-02-06 14:16

    Here's a Swift extension to NSLocale that returns an array of Swift-friendly Locale structs with the country names and country codes. It could easily be extended to include other country data.

    extension NSLocale {
    
        struct Locale {
            let countryCode: String
            let countryName: String
        }
    
        class func locales() -> [Locale] {
    
            var locales = [Locale]()
            for localeCode in NSLocale.ISOCountryCodes() {
                let countryName = NSLocale.systemLocale().displayNameForKey(NSLocaleCountryCode, value: localeCode)!
                let countryCode = localeCode as! String
                let locale = Locale(countryCode: countryCode, countryName: countryName)
                locales.append(locale)
            }
    
            return locales
        }
    
    }
    

    And then it's easy to get the array of countries like this:

    for locale in NSLocale.locales() {
        println("\(locale.countryCode) - \(locale.countryName)")
    }
    

提交回复
热议问题