整数溢出在 Swift 中给出 EXC_BAD_INSTRUCTION

Integer overflow gives EXC_BAD_INSTRUCTION in Swift

在弄乱 Swift 时,我注意到当 64 位整数溢出时,我得到以下错误:

file:///Users/user/Documents/playground/MyPlayground.playground/: error: Playground execution aborted: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

func fibonacci(which: Int) -> (fibOf: Int, isEqualTo: Int) {
    var i = 1, j = 1

    for var k = 2; k < which; k += 1 {
        let tmp = i + j // this line is highlighted when error occurs
        j = i
        i = tmp
    }

    return (which, i)
}

print (fibonacci(92))
print (fibonacci(93)) // this triggers an error

第一次调用,即以 92 作为参数,将 运行 正常。但是,当提供 93 值时,我得到了不相关的 EXC_BAD_INSTRUCTION 错误。这是一个错误还是什么?通常我希望它溢出。

这是预期的行为。如果要溢出,需要使用overflow operators.

  • 溢出加法(&+
  • 溢出减法(&-
  • 溢出乘法(&*