嘗試做這樣的事情:
// get the localized country name (in my case, it's US English)
let englishLocale : NSLocale = NSLocale.init(localeIdentifier : "en_US")
// get the current locale
let currentLocale = NSLocale.currentLocale()
var theEnglishName : String? = englishLocale.displayNameForKey(NSLocaleIdentifier, value: currentLocale.localeIdentifier)
if let theEnglishName = theEnglishName
{
let countryName = theEnglishName.sliceFrom("(", to: ")")
print("the localized country name is \(countryName)")
}
與這個輔助功能that I found here:
import Foundation
extension String {
func sliceFrom(start: String, to: String) -> String? {
return (rangeOfString(start)?.endIndex).flatMap { sInd in
(rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in
substringWithRange(sInd..<eInd)
}
}
}
}
我想通了這一點通過研究爲this related question。
一個真正的Swift 3答案會使用Locale而不是NSLocale。 – Moritz
是的,我同意,但是,對於使用NSLocale的IOS 8,如果您使用的是Locale,則意味着IOS 8不會返回正確的響應。 –