LoginSignup
10
10

More than 5 years have passed since last update.

Swiftで国名コードの変換

Posted at

iOSで国名コードの数値から国名を取得する方法のメモ。

NSLocaleに含まれる国名コード一覧

ISO 3166-1の一覧はiOSのNSLocaleでも取得できるのだが、こちらは"JP"のようなAlpha-2 codeのArrayのみが用意されている。

NSLocale.ISOCountryCodes() // ["AD", "AE", "AF", "AG", "AI",...]

数値コードから国名への変換

数値コードからのAlpha-2やShort Nameを取得できるテーブルがなかったので、独自に変数に定義しておくことにした。

サンプルとしては以下のようなコードになる。Dictionaryの全文は長くなるので省略。

// Sample ISO 3166-1 Dictionary
let ISOCountryCodes = [250: "FR"]

// Sample input value
let countryNumericCode = 250

// Convert to country name
let countryCode = ISOCountryCodes[countryNumericCode]
let countryName = NSLocale.currentLocale().displayNameForKey(NSLocaleCountryCode, value: countryCode) // "France"

バリューに国名を定義せずに一度"JP"のような表記を経由しているのは、多言語対応のため。
currentLocaleを使うことで、デバイスの設定に合わせた表記で国名を取得できる。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10