本文介绍了Swift 通过 unicode 将国家/地区代码转换为表情符号标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快速的方法来改变类似的东西:

I'm looking for a quick way to turn something like:

let germany = "DE"

进入

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

即,D1f1e9E1f1ea 的映射是什么我正在查看字符串的 .utf8 ,但这返回一个整数.

ie, what's the mapping of D to 1f1e9 and E to 1f1eaI was looking at .utf8 for the string, but this returns an integer.

FWIW 我的总体目标是能够采用任意国家代码并获得相应的表情符号标志.

FWIW my general goal is to be able to take an arbitrary country code and get the corresponding emoji flag.

我也可以只拿着一张桌子来做这个映射,如果它在某处可用的话.我用谷歌搜索,但没有找到.

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:

func flag(country:String) -> String {
    let base = 127397
    var usv = String.UnicodeScalarView()
    for i in country.utf16 {
        usv.append(UnicodeScalar(base + Int(i)))
    }
    return String(usv)
}

let s = flag("DE")

EDIT 糟糕,不需要通过嵌套的 String.UnicodeScalarView 结构.事实证明, String 有一个 append 方法正是为了这个目的.所以:

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:

func flag(country:String) -> String {
    let base : UInt32 = 127397
    var s = ""
    for v in country.unicodeScalars {
        s.append(UnicodeScalar(base + v.value))
    }
    return s
}

EDIT 哎呀,在 Swift 3 中,他们取消了将 UnicodeScalar 附加到字符串的能力,并使 UnicodeScalar 初始值设定项可失败(Xcode 8 种子 6),所以现在看起来像这样:

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:

func flag(country:String) -> String {
    let base : UInt32 = 127397
    var s = ""
    for v in country.unicodeScalars {
        s.unicodeScalars.append(UnicodeScalar(base + v.value)!)
    }
    return String(s)
}

这篇关于Swift 通过 unicode 将国家/地区代码转换为表情符号标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:30