How to get the country name from the alpha-2 country code in Swift

1 Answer

0 votes
import Foundation

// Function that returns the English country name for a given alpha‑2 code
func getCountryName(_ code: String) -> String {
    // Ask the Locale system for the localized region name
    // "en" ensures the result is in English
    let locale = Locale(identifier: "en")

    // localizedString(forRegionCode:) returns the country name
    return locale.localizedString(forRegionCode: code) ?? "Unknown country"
}

print(getCountryName("US")) // United States
print(getCountryName("GB")) // United Kingdom
print(getCountryName("AU")) // Australia



/*
run:

United States
United Kingdom
Australia

*/

 



answered Jun 17 by avibootz
...