2014-06-19 15 views
5

Swift'deki tüm ülke isimleriyle nasıl dizi alabilirim? Ben Objective-C vardı kodunu dönüştürmek için denedim bu:Swift - Ülkelerin listesini al

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]; 
    } 

Ve Swift de buradan geçemez:

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

sizin bilen var mı bunun hakkında?

Teşekkür

cevap

3

İlk böylece yerine argüman parantez gerektiren bir işlemdir. İkincisi, NSLocale ve ISOCountryCodes() civarında parantez gerekmez. Ayrıca, arrayWithCapacity, dilden kaldırıldığı anlamına gelir. Bu

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

ben dizideki sıfır elemanları alıyorum! – Kirti

1

O ISOCountryCodes() olacağını tüm ISOCountryCodes değil bir Mülkiyet

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

İşte ülke adları ve ülke kodları ile Swift dostu Yerel yapılar dizisi döndürür NSLocale bir Swift uzantısı biraz gibi bu bir çalışma versiyonu olacaktır. Diğer ülke verilerini de içerecek şekilde genişletilebilir.

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 
    } 

} 

Ve sonra bu gibi ülkelerde dizisini almak kolaydır:

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