I needed a similar conversion for ISO 3166-1 country codes. iOS gave me a 2 letter code, but I needed a 3 letter code. Here is my solution:
Sample example code (if you have an iso-countries.json file in the lukes GIT project format)
import UIKit import CoreTelephony class CountryCode { internal var _countries: [String: [AnyHashable: Any]]? internal var countries: [String: [AnyHashable: Any]]? { get { if _countries == nil { _countries = countriesDictionary() } return _countries } } func convertToThreeCharacterCountryCode(twoCharacterCountryCode: String) -> String? { let country = countries?[twoCharacterCountryCode.uppercased()] return country?["alpha-3"] as? String } fileprivate func countriesDictionary() -> [String: [AnyHashable: Any]] { var countries = [String: [AnyHashable: Any]]() guard let url = Bundle.main.url(forResource: "iso-countries", withExtension: "json") else { return countries } do { let data = try Data(contentsOf: url) if let dictionaries = try JSONSerialization.jsonObject(with: data, options: []) as? [[AnyHashable: Any]] { for countryDictionary in dictionaries { if let key = countryDictionary["alpha-2"] as? String { countries[key] = countryDictionary } } return countries } return countries } catch { return countries } } }
You might consider making this a Singleton class, so countries only need to load once. I didn’t do it the way I didn’t want to keep the countries in my memory (in my application this was necessary only once at startup).
Bocaxica
source share