Swift 的 IsoCountryCodes

Platform version Swift Version

Iso 国家代码 - 我们讨论过的,用于定义国家、附属领土和特殊地理区域代码的东西。

是什么?

这是一个 iOS Swift 库/类文件,它根据您提供的 alpha2alpha3数字 值进行简单查找。目前,它包含 ISO 3166-1 中分配了官方代码的所有 249 个国家、地区或具有地理意义的区域。

特性

这个库返回国家的 ISO 代码、名称和货币。

用法

您可以通过数字、alpha-2 或 alpha-3 格式进行搜索。 搜索 ISO 代码返回一个结构体。

print(IsoCountryCodes.find(key: "020").name) //Andorra
print(IsoCountryCodes.find(key: "TK").name) //Tokelau
print(IsoCountryCodes.find(key: "TKL").currency) //NZD

您也可以按国家名称、货币或呼叫/拨号代码搜索

dump(IsoCountryCodes.searchByName("Netherlands")
print(IsoCountryCodes.searchByCurrency("EUR").count ) // 31
print(IsoCountryCodes.searchByCallingCode("+31").first ) // Netherlands

let country = IsoCountryCodes.searchByName("Netherlands")
dump(country) // This dumps the full struct in console

这会返回一个 IsoCountryInfo 结构体

 IsoCountryCodes.IsoCountryInfo
    - name: Netherlands
    - numeric: 528
    - alpha2: NL
    - alpha3: NLD
    - calling: +31
    - currency: EUR
    - continent: EU

按名称搜索不区分大小写和变音符号

dump(IsoCountryCodes.searchByName("netherlands"))
dump(IsoCountryCodes.searchByName("NETHERLANDS"))

dump(IsoCountryCodes.searchByName("Réunion"))
dump(IsoCountryCodes.searchByName("Reunion"))

如果未找到完全匹配项,则尝试部分匹配

// Full name is "Venezuela, Bolivarian Republic of"
dump(IsoCountryCodes.searchByName("Venezuela"))

但如果搜索结果含糊不清,则不返回任何内容

// There are two Virgin Islands country codes:
// "Virgin Islands, British" and "Virgin Islands, U.S."
dump(IsoCountryCodes.searchByName("Virgin Islands"))

国旗的乐趣

从国家代码检索相应的表情符号国旗。(感谢 @lorismaz 添加此功能)

let emojiString = IsoCountries.flag(countryCode: "NL")
// Prints 🇳🇱

let emojiString = IsoCountryCodes.find(key: "USA").flag
// Prints 🇺🇸

检索小数位数

检索国家货币的小数位数。 这在将某种货币的金额转换为数字时很有用。 例如,计算 1 欧元包含多少欧分(100 欧分),或者科威特第纳尔; 1 KD = 1000 费尔。 在与银行或支付提供商合作时,这很方便。(感谢 @mohameditani 添加此功能)。

func transformToDigits(price: Double, country: IsoCountryInfo) -> Double {
  let fractionDigits = country.fractionDigits
  let amount = price * pow(10.0, Double(fractionDigits))
  return amount
}

let priceOfCoffee = 2.05
let country = IsoCountryCodes.searchByName("Italy") // fractionDigits for Italy is 2
let digits = transformToDigits(priceOfCoffee, country)
// 205 cents

用法

复制/添加文件到您的项目中

许可

“想怎么用就怎么用”的许可。 使用它或滥用它。 只要在文件顶部保留我的名字即可。