swift - 无效的狗脸标量
问题描述
我以为我非常了解 Swift 中的 Unicode 标量,但狗脸表情符号证明我错了。
for code in "".utf16 {
print(code)
}
UTF-16 代码是55357
和56374
。在十六进制中,即d83d
和dc36
。
现在:
let dog = "\u{d83d}\u{dc36}"
我没有得到一个带有“”的字符串,而是得到一个错误:
无效的 unicode 标量
我尝试使用 UTF-8 代码,但也没有用。不会抛出错误,而是返回“ð¶”而不是狗脸。
这里有什么问题?
解决方案
\u{nnnn}
转义序列需要一个Unicode 标量值,而不是 UTF-16 表示(具有高和低代理):
for code in "".unicodeScalars {
print(String(code.value, radix: 16))
}
// 1f436
let dog = "\u{1F436}"
print(dog) //
可以在Is there a way to create a String from utf16 array in swift 中找到从其 UTF-16 表示重建字符串的解决方案?. 例如:
let utf16: [UInt16] = [ 0xd83d, 0xdc36 ]
let dog = String(utf16CodeUnits: utf16, count: utf16.count)
print(dog) //
推荐阅读
- python - 切片列表是字典的值
- python - (django)我想在创建用户时根据他们的角色创建一个指定的模型实例
- sorting - 正确排序数据框
- flutter - DateTime.isAtSameMomentAs() 不适合我
- google-cloud-platform - 为什么 Google GCP 在创建新存储桶时会默认创建 Storage Legacy 角色?
- python - AWS boto3 调用 lambda 返回无负载
- java - 我的 Java Spring 项目构建成功,但在日志中给我错误
- docker-compose - 带有 Strapi 的 NextJS docker 在启动时退出
- javascript - 如何在 Typescript 中向 Winston 记录器添加自定义功能?
- next.js - 如何让 Next.js 应用程序与 Cloudflare Workers - Workers Sites 一起使用