2014-06-19 11 views
5

Come posso ottenere un array con tutti i nomi dei Paesi in Swift? Ho cercato di convertire il codice che avevo in Objective-C, che è stato questo:Swift - Ottieni l'elenco dei Paesi

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

E a Swift non riesco a passare da qui:

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

Qualcuno di voi sa a questo proposito?

Grazie

risposta

3

Prima di tutto ISOCountryCodes richiede argomento parentesi così invece sarebbe ISOCountryCodes(). In secondo luogo, non hai bisogno di parentesi intorno a NSLocale e ISOCountryCodes(). Inoltre, arrayWithCapacity è deprecato, il che significa che viene rimosso dalla lingua. Una versione funzionante di questo sarebbe un po 'come questo

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

sto ottenendo zero elementi in serie! – Kirti

1

Si tratta di un'operazione non una proprietà

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

Ecco un'estensione Swift per NSLocale che restituisce un array di struct Locale Swift-amichevoli con i nomi dei paesi e codici di paese. Potrebbe essere facilmente esteso per includere altri dati nazionali.

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 
    } 

} 

E poi è facile ottenere la serie di paesi come questo:

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