Home > database >  How convert a Swift string created with "\u{ea12}" back to its hex value / string "e
How convert a Swift string created with "\u{ea12}" back to its hex value / string "e

Time:05-10

TL;DR

A Swift string is created with a single character like this:

let iconCode = "\u{ea12}"

How can I use convert iconCode back to output the hex value "ea12" instead?

Details:

Several years ago a custom icon font was added to an iOS app. Back then the font was shipped with a CSS file declaring a css-class for each icon:

.icon-XYZ:before { content: '\ea12'; }    /* some icon */

This was translated into Swift to hardcode the icons into the app:

let icons: [String: String] = [
    "XYZ": "\u{ea12}",
    "abc": "\u{e07}",
    "123": "\u{2c}",
    ...
]

func getIcon(withId id: String) -> String {
    return icon[id] ?? ""
}

Meanwhile the CSS is lost and needs to be re-created. How can I do this:

func dumpCSS() {
     for (id, icon) in icons {
         guard let data = icon.data(using: .utf8) else { print("error"); return }
         let code = data.map { String(format: "hhx", $0) }.joined()
         print(".icon-\(id):before { content: '\\\(code)'; }")
     }
}

.icon-123:before { content: '\2c'; }       // OK
.icon-XYZ:before { content: '\eea892'; }   // wrong
.icon-abc:before { content: '\e0b887'; }   // wrong

CodePudding user response:

CSS escapes use the unicode code point value, so you should definitely not use the UTF8 encoding. Instead, use unicodeScalars to get all the code points in the string.

 for (id, icon) in icons {
     let codePoints = icon.unicodeScalars

     // assuming each icon can have multiple code points
     let escapeSequences = codePoints.map { "\\\(String($0.value, radix: 16))" }.joined()

     print(".icon-\(id):before { content: '\(escapeSequences)'; }")
 }
  • Related