我可以直接在 Swift 字符与其 Unicode 数值之间进行转换吗?那是:
var i:Int = ... // A plain integer index.
var myCodeUnit:UInt16 = myString.utf16[i]
// Would like to say myChar = myCodeUnit as Character, or equivalent.
Run Code Online (Sandbox Code Playgroud)
或者...
var j:String.Index = ... // NOT an integer!
var myChar:Character = myString[j]
// Would like to say myCodeUnit = myChar as UInt16
Run Code Online (Sandbox Code Playgroud)
我可以说:
myCodeUnit = String(myChar).utf16[0]
Run Code Online (Sandbox Code Playgroud)
但这意味着为每个字符创建一个新字符串。我已经这样做了数千次(解析文本),因此很多新字符串立即被丢弃。
小智 1
我采访了一位从事 Unicode 工作的 Apple 工程师,他说他们还没有完成字符串中 unicode 字符的实现。您想要获得一个代码单元还是一个完整的字符?因为获取完整 unicode 字符的唯一且正确的方法是在字符串上使用 for every 循环。IE
for c in "hello" {
// c is a unicode character of type Character
}
Run Code Online (Sandbox Code Playgroud)
但是,目前尚未实施。
| 归档时间: |
|
| 查看次数: |
5902 次 |
| 最近记录: |