Last active
June 12, 2025 15:09
-
-
Save dineybomfim/a4d88330111032e212ef66446d19dbcb to your computer and use it in GitHub Desktop.
Have you ever wondered how to convert and/or use alpha 2 and alpha 3 country codes seamlessly with native Swift Locale? Here is the answer: There is a tricky, very cost-efficient that can guarantee to find valid ISO Alpha-2 and Alpha-3 country codes (ISO 3166 international standard). NO EXTERNAL FILE IS NEEDED!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension Locale { | |
private static var availableRegions: [Locale] = { Locale.availableIdentifiers.map { Locale(identifier: $0) } }() | |
init?(isoCode: String, from: Locale = .autoupdatingCurrent) { | |
guard let locale = from.locale(isoCode: isoCode) else { return nil } | |
self = locale | |
} | |
func alpha2Code(from isoCode: String) -> String? { | |
let regionName = localizedString(forRegionCode: isoCode) ?? "" | |
return Self.availableRegions.first(where: { localizedString(forRegionCode: $0.regionCode ?? "") == regionName })?.regionCode | |
} | |
func locale(isoCode: String) -> Locale? { | |
let alpha2Code = alpha2Code(from: isoCode) | |
var matchingLocale: Locale? | |
for region in Self.availableRegions { | |
if region.regionCode == alpha2Code { | |
if region.languageCode == languageCode { | |
return region | |
} else if matchingLocale == nil { | |
matchingLocale = region | |
} | |
} | |
} | |
return matchingLocale | |
} | |
} | |
// Usage in playground | |
Locale(isoCode: "ARE") // United Arab Emirates | |
Locale(isoCode: "are") // United Arab Emirates | |
Locale(isoCode: "ar") // Argentina | |
Locale(isoCode: "br") // Brazil | |
Locale(isoCode: "bra") // Brazil | |
Locale(isoCode: "BRA") // Brazil | |
Locale(isoCode: "US") // United States of America | |
Locale(isoCode: "USA") // United States of America | |
Locale(isoCode: "ARE", from: Locale(identifier: "en")) // English - United Arab Emirates | |
Locale(isoCode: "ARE", from: Locale(identifier: "ar")) // Arabic - United Arab Emirates | |
Locale(identifier: "en").locale(isoCode: "br") // English - Brazil | |
Locale(identifier: "es").locale(isoCode: "mx") // Spanish - Mexico | |
Locale.autoupdatingCurrent.alpha2Code(from: "ARE") // AE | |
Locale.autoupdatingCurrent.alpha2Code(from: "are") // AE | |
Locale.autoupdatingCurrent.alpha2Code(from: "aRe") // AE | |
Locale.autoupdatingCurrent.alpha2Code(from: "ae") // AE | |
Locale.autoupdatingCurrent.alpha2Code(from: "Ae") // AE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment