2014-06-19 143 views
5

如何在Swift中获得包含所有国家/地区名称的数组? 我试图代码我不得不在Objective-C,这是转换这样的:Swift - 获取国家列表

if (!pickerCountriesIsShown) { 
    NSMutableArray *countries = [NSMutableArray arrayWithCapacity: [[NSLocale ISOCountryCodes] count]]; 

    for (NSString *countryCode in [NSLocale ISOCountryCodes]) 
    { 
     NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]]; 
     NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier]; 
     [countries addObject: country]; 
    } 

而且在斯威夫特我不能从这里经过:

 if (!countriesPickerShown) { 
     var countries: NSMutableArray = NSMutableArray() 
     countries = NSMutableArray.arrayWithCapacity((NSLocale.ISOCountryCodes).count) // Here gives the Error. It marks NSLocale.ISOCountryCodes and .count 

难道你们有谁知道对这个?

感谢

回答

3

所有ISOCountryCodes首先需要论证括号这样反而会是ISOCountryCodes()。其次,你不需要围绕NSLocaleISOCountryCodes()括号。而且,arrayWithCapacity已被弃用,这意味着它从语言中被删除。这方面的一个工作版本会有点像这个

if (!countriesPickerShown) { 
    var countries = NSMutableArray() 
    countries = NSMutableArray(capacity: (NSLocale.ISOCountryCodes().count)) 
} 
+0

我得到的数组零个元素! – Kirti

1

这是一个操作不是一个属性

if let codes = NSLocale.ISOCountryCodes() { 
    println(codes) 
} 
4

这里有一个斯威夫特扩展NSLocale返回斯威夫特友好的语言环境结构的数组与国名和国家代码。它可以很容易地扩展到包括其他国家的数据。

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 
    } 

} 

然后很容易得到国家的类似这样的数组:

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