首页 > 解决方案 > 无效的狗脸标量

问题描述

我以为我非常了解 Swift 中的 Unicode 标量,但狗脸表情符号证明我错了。

for code in "".utf16 {
    print(code)
}

UTF-16 代码是5535756374。在十六进制中,即d83ddc36

现在:

let dog = "\u{d83d}\u{dc36}"

我没有得到一个带有“”的字符串,而是得到一个错误:

无效的 unicode 标量

我尝试使用 UTF-8 代码,但也没有用。不会抛出错误,而是返回“ð¶”而不是狗脸。

这里有什么问题?

标签: swiftstringunicode

解决方案


\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) // 

推荐阅读