Skip to content

Instantly share code, notes, and snippets.

@anoopsankar
Created July 7, 2021 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anoopsankar/55fd3a68fdebf9ca12b36e1e340e70ab to your computer and use it in GitHub Desktop.
Save anoopsankar/55fd3a68fdebf9ca12b36e1e340e70ab to your computer and use it in GitHub Desktop.
Find Unicode / Emoji flag based on country code in Swift 5
func unicodeFlag(countryCode: String) -> String {
// expects a 2-letter ISO code of the country
// Unicode flags are generated by taking the 2 letter ISO code of the country
// and mapping them to the regional indicator symbols. Font ligatures are used
// to make them into a single glymph. A more detailed explanation is available
// here -> https://esham.io/2014/06/unicode-flags
// This code is based on this stackoverflow answer for Java
// https://stackoverflow.com/questions/30494284/android-get-country-emoji-flag-using-locale/35849652#35849652
let flagOffset: UInt32 = 0x1F1E6 // REGIONAL INDICATOR SYMBOLS starting point ("A")
let asciiOffset: UInt32 = 0x41 // ASCII START
var flag = ""
// Split the symbols into their scalars
for scalar in countryCode.unicodeScalars {
// Compute the regional indicator symbol scalar
flag.append(String(Unicode.Scalar(scalar.value - asciiOffset + flagOffset)!))
}
return flag
}
print(unicodeFlag(countryCode: "IN"))
print(unicodeFlag(countryCode: "SE"))
print(unicodeFlag(countryCode: "DE"))
print(unicodeFlag(countryCode: "SC"))
/*
Output:
🇮🇳
🇸🇪
🇩🇪
🇸🇨
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment