swiftfoundation

How to determine the continent name by a country code in Swift


I have an ISO two-letter country code (e.g., "US") and need to determine its continent's name.

I know about the continent property of Locale.Region, which is also a Locale.Region instance, but it doesn't have a name, only a BCP 47 identifier.


Solution

  • To get a localised name of a region, Locale has method localizedString(forRegionCode:).

    So, the first step is to obtain the continent's ID:

    let continentID = Locale.Region(stringLiteral: countryCode).continent?.identifier
    

    Then Locale will tell you its localised name:

    let continentName = Locale.current.localizedString(forRegionCode: continentID)