2015-01-10 161 views
16

我已經看到兩個類似的問題,但這些問題的答案不適用於我。我有一箇舊項目,手動輸入一組方括號內的國家列表。如何獲得Swift ios中的國家/地區列表?

我可以很容易地在我的pickerView中使用它,但我想知道是否有更高效的方法來做到這一點?

我將在UIPickerView中使用國家列表。

回答

23

您可以使用NSLocale類的ISOCountryCodes()方法獲取國家列表,該方法返回[AnyObject]的數組,您將其作爲[String]進行投射。從那裏,你通過使用NSLocale的displayNameForKey方法得到國家名稱。它看起來像這樣:

var countries: [String] = [] 

for code in NSLocale.ISOCountryCodes() as [String] { 
    let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code]) 
    let name = NSLocale(localeIdentifier: "en_UK").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)" 
    countries.append(name) 
    } 

println(countries) 
8

同伊恩的,但更短的

let countries = NSLocale.ISOCountryCodes().map { (code:String) -> String in 
    let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code]) 
    return NSLocale(localeIdentifier: "en_US").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)" 
} 

print(countries) 
2

也很本地化的國家顯示的名稱一個很好的做法。因此,除了vedo27回答將是:

let countriesArray = NSLocale.ISOCountryCodes().map { (code:String) -> String in 
     let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code]) 
     let currentLocaleID = NSLocale.currentLocale().localeIdentifier 
     return NSLocale(localeIdentifier: currentLocaleID).displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)" 
    } 
5

這裏是@ vedo27的答案斯威夫特3

let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in 
    let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code]) 
    return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)" 
} 
3

斯威夫特3宣稱爲var

var countries: [String] { 
    let myLanguageId = "en" // in which language I want to show the list 
    return NSLocale.isoCountryCodes.map { 
     return NSLocale(localeIdentifier: myLanguageId).localizedString(forCountryCode: $0) ?? $0 
    } 
} 
+0

localizedString(forCountryCode:code)僅適用於iOS10 – Rajesh73

+0

是的,這是正確的 –

8

SWIFT 3和4

var countries: [String] = [] 

for code in NSLocale.isoCountryCodes as [String] { 
    let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code]) 
    let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)" 
    countries.append(name) 
} 

print(countries) 
相關問題