Swift - 获取国家列表

6

我该如何在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];
    }

在Swift中,我无法从这里传递:
        if (!countriesPickerShown) {
        var countries: NSMutableArray = NSMutableArray()
        countries = NSMutableArray.arrayWithCapacity((NSLocale.ISOCountryCodes).count) // Here gives the Error. It marks NSLocale.ISOCountryCodes and .count

你们中有谁了解这个吗?

谢谢

3个回答

6
这里是一个扩展NSLocale的Swift代码片段,它返回一个包含国家名称和国家代码的Swift可识别的Locale结构体数组。可以很容易地扩展到包括其他国家数据。
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)")
}

3

首先,ISOCountryCodes需要参数括号,所以正确的写法应该是ISOCountryCodes()。其次,NSLocaleISOCountryCodes()不需要加上括号。此外,arrayWithCapacity已经被废弃,意味着它已从语言中移除。一个可行的版本应该是这样的:

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

我在数组中得到了零个元素! - Kirti

2
这是一个操作而不是属性。
if let codes = NSLocale.ISOCountryCodes() {
    println(codes)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接