【问题标题】:Getting character ASCII value as an Integer in Swift在 Swift 中将字符 ASCII 值作为整数获取
【发布时间】:2021-07-29 22:09:05
【问题描述】:
我一直在尝试将字符 ascii 代码作为 int 获取,以便我可以修改它并通过做一些数学运算来更改字符。但是我发现这样做很困难,因为我在不同类型的整数之间遇到转换错误并且似乎找不到答案
var n:Character = pass[I] //using the string protocol extension
if n.isASCII
{
var tempo:Int = Int(n.asciiValue)
temp += (tempo | key) //key and temp are of type int
}
【问题讨论】:
标签:
swift
character-encoding
integer
character
ascii
【解决方案1】:
在 Swift 中,Character 不一定是 ASCII 码。例如,返回 "?" 的 ascii 值是没有意义的,这需要大的 unicode 编码。这就是为什么asciiValue 属性有一个optional UInt8 值,它被注释为UInt8?。
最简单的解决方案
既然你自己检查了isAscii这个角色,你就可以放心地使用!进行无条件解包:
var tempo:Int = Int(n.asciiValue!) // <--- just change this line
更优雅的选择
您还可以利用可选绑定,当没有 ascii 值(即 n 不是 ASCII 字符)时,可选绑定为 nil:
if let tempo = n.asciiValue // is true only if there is an ascii value
{
temp += (Int(tempo) | key)
}