Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the ๐Ÿ‡ฉ๐Ÿ‡ช character represented in Swift strings?

Like some other emoji characters, the 0x0001F1E9 0x0001F1EA combination (German flag) is represented as a single character on screen although it is really two different Unicode character points combined. Is it represented as one or two different characters in Swift?

like image 965
Max Yankov Avatar asked Jun 02 '14 22:06

Max Yankov


2 Answers

With Swift 5, you can iterate over the unicodeScalars property of a flag emoji character in order to print the Unicode scalar values that compose it:

let emoji: Character = "๐Ÿ‡ฎ๐Ÿ‡น"
for scalar in emoji.unicodeScalars {
    print(scalar)
}
/*
 prints:
 ๐Ÿ‡ฎ
 ๐Ÿ‡น
 */

If you combine those scalars (that are Regional Indicator Symbols), you get a flag emoji:

let italianFlag = "๐Ÿ‡ฎ" + "๐Ÿ‡น"
print(italianFlag) // prints: ๐Ÿ‡ฎ๐Ÿ‡น
print(italianFlag.count) // prints: 1

Each Unicode.Scalar instance also has a property value that you can use in order to display a numeric representation of it:

let emoji: Character = "๐Ÿ‡ฎ๐Ÿ‡น"
for scalar in emoji.unicodeScalars {
    print(scalar.value)
}
/*
 prints:
 127470
 127481
 */

You can create Unicode scalars from those numeric representations then associate them into a string:

let scalar1 = Unicode.Scalar(127470)
let scalar2 = Unicode.Scalar(127481)
let italianFlag = String(scalar1!) + String(scalar2!)
print(italianFlag) // prints: ๐Ÿ‡ฎ๐Ÿ‡น
print(italianFlag.count) // prints: 1

If needed, you can use Unicode.Scalar's escaped(asASCII:) method in order to display a string representation of the Unicode scalars (using ASCII characters):

let emoji: Character = "๐Ÿ‡ฎ๐Ÿ‡น"
for scalar in emoji.unicodeScalars {
    print(scalar.escaped(asASCII: true))
}
/*
 prints:
 \u{0001F1EE}
 \u{0001F1F9}
 */
let italianFlag = "\u{0001F1EE}\u{0001F1F9}"
print(italianFlag) // prints: ๐Ÿ‡ฎ๐Ÿ‡น
print(italianFlag.count) // prints: 1

String's init(_:radix:uppercase:) may also be relevant to convert the scalar value to an hexadecimal value:

let emoji: Character = "๐Ÿ‡ฎ๐Ÿ‡น"
for scalar in emoji.unicodeScalars {
    print(String(scalar.value, radix: 16, uppercase: true))
}
/*
 prints:
 1F1EE
 1F1F9
 */
let italianFlag = "\u{1F1EE}\u{1F1F9}"
print(italianFlag) // prints: ๐Ÿ‡ฎ๐Ÿ‡น
print(italianFlag.count) // prints: 1
like image 79
Imanou Petit Avatar answered Sep 22 '22 14:09

Imanou Petit


let flag = "\u{1f1e9}\u{1f1ea}"

then flag is ๐Ÿ‡ฉ๐Ÿ‡ช .

For more regional indicator symbols, see:
http://en.wikipedia.org/wiki/Regional_Indicator_Symbol

like image 42
NSDeveloper Avatar answered Sep 23 '22 14:09

NSDeveloper