Swift turn a country code into a emoji flag via unicode

后端 未结 7 875
日久生厌
日久生厌 2020-12-07 14:08

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

let germany = \"DE\" 

into

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


        
7条回答
  •  日久生厌
    2020-12-07 14:28

    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 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 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)
    }
    

提交回复
热议问题