I'm looking for a quick way to turn something like:
let germany = "DE"
into
let flag = "\u{1f1e9}\u{1f1ea}"
ie, what's the mapping of D
to 1f1e9
and E
to 1f1ea
I was looking at .utf8
for the string, but this returns an integer.
FWIW my general goal is to be able to take an arbitrary country code and get the corresponding emoji flag.
EDIT: I'm also fine with just holding a table that does this mapping if its available somewhere. I googled around but didn't find it.
Here's a general formula for turning a two-letter country code into its emoji flag:
EDIT Ooops, no need to pass through the nested String.UnicodeScalarView struct. It turns out that String has an
append
method for precisely this purpose. So:EDIT Oooops again, in Swift 3 they took away the ability to append a UnicodeScalar to a String, and they made the UnicodeScalar initializer failable (Xcode 8 seed 6), so now it looks like this:
To give more insight into matt answer
Swift 2 version
Two optimizations of matt's answer.
Here is the code.
For a more functional approach, using no mutable variables, use this:
Where the
|>
operator is the function application operator, working like a "pipe" for a more natural reading order: We take the scalars, map them into new scalars, turn that into a view, and that into a string.It's defined like so:
Without custom operators, we can still do without mutable state, like so:
But IMHO, this reads a little "backwards", since the natural flow of operations read neither out-in, nor in-out, but a little bit of both.
If anyone looking for solution in ObjectiveC here is convenient category:
test:
output: