问题描述
let a = Character("0").asciiValue!
let b = Character(" ").asciiValue!
let c = b - a
上述代码运行时编译器会产生如下问题
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
分析
a 与 b 均为 UInt8,因此如果 b - a 的结果为负,UInt8 就无法表示,因此产生问题
解决
在做减法前,将 a 和 b 分别转为有符号的类型即可
网友评论