TL;博士
Swift 字符串是用单个字符创建的,如下所示:
let iconCode = "\u{ea12}"
如何使用convert iconCode
来输出十六进制值"ea12"
?
详细信息:
几年前,iOS 应用程序中添加了自定义图标字体。当时,字体附带了一个 CSS 文件,为每个图标声明了一个 css 类:
.icon-XYZ:before { content: '\ea12'; } /* some icon */
这被翻译成 Swift,将图标硬编码到应用程序中:
let icons: [String: String] = [
"XYZ": "\u{ea12}",
"abc": "\u{e07}",
"123": "\u{2c}",
...
]
func getIcon(withId id: String) -> String {
return icon[id] ?? ""
}
同时 CSS 丢失并且需要重新创建。我该怎么做:
func dumpCSS() {
for (id, icon) in icons {
guard let data = icon.data(using: .utf8) else { print("error"); return }
let code = data.map { String(format: "%02hhx", $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
最佳答案
CSS 转义使用 unicode 代码点值,因此绝对不应该使用 UTF8 编码。相反,请使用 unicodeScalars
获取字符串中的所有代码点。
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)'; }")
}
关于swift - 如何将使用 "\u{ea12}"创建的 Swift 字符串转换回其十六进制值/字符串 "ea12"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72173295/