Created
July 7, 2021 13:17
-
-
Save anoopsankar/55fd3a68fdebf9ca12b36e1e340e70ab to your computer and use it in GitHub Desktop.
Find Unicode / Emoji flag based on country code in Swift 5
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
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