如何将使用“\u{ea12}”创建的 Swift 字符串转换回其十六进制值/字符串 "ea12"?
How convert a Swift string created with "\u{ea12}" back to its hex value / string "ea12"?
TL;DR
Swift 字符串是用单个字符创建的,如下所示:
let iconCode = "\u{ea12}"
如何使用 convert iconCode
返回输出十六进制值 "ea12"
?
详情:
几年前,自定义图标字体被添加到 iOS 应用程序中。当时字体附带一个 CSS 文件,为每个图标声明一个 css-class:
.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", [=15=]) }.joined()
print(".icon-\(id):before { content: '\\(code)'; }")
}
}
.icon-123:before { content: 'c'; } // 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([=10=].value, radix: 16))" }.joined()
print(".icon-\(id):before { content: '\(escapeSequences)'; }")
}
TL;DR
Swift 字符串是用单个字符创建的,如下所示:
let iconCode = "\u{ea12}"
如何使用 convert iconCode
返回输出十六进制值 "ea12"
?
详情:
几年前,自定义图标字体被添加到 iOS 应用程序中。当时字体附带一个 CSS 文件,为每个图标声明一个 css-class:
.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", [=15=]) }.joined()
print(".icon-\(id):before { content: '\\(code)'; }")
}
}
.icon-123:before { content: 'c'; } // 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([=10=].value, radix: 16))" }.joined()
print(".icon-\(id):before { content: '\(escapeSequences)'; }")
}