Swift: 如何禁用函数的整数溢出/下溢陷阱

Swift: How to disable integer overflow / underflow traps for a function

我正在将一些旧的 C 代码导入 swift 项目,并将其移植到纯 swift 代码中。

其中一些会 "encryption" 其中它会做类似

的事情
let a = UInt8(x) // e.g. 30
let b = a - 237

在 C 中,这只是下溢和回绕,这对于这个特定的函数来说很好。

在 swift 中,这会触发 fatalError 并以 EXC_BAD_INSTRUCTION 终止我的程序,因为 swift 默认情况下旨在捕获整数 over/underflow.

我知道我可以通过使用 -Ofast 进行编译在整个项目级别关闭此检查,但我真的很想关闭这一行代码的溢出检查(或者可能只是具体功能本身)。

注意:我特别想保留 C 函数的行为,而不仅仅是提升 Int32 或 Int64

这个特定的术语似乎很难google。


更新:答案是Overflow operators,也就是

我在之前的搜索中找不到它们。糟糕

您可以使用 addWithOverflow 或 subtractWithOverflow class Int、UInt8 等类型的方法

例如let b = UInt8.subtractWithOverflow(a, 237)

除了溢出运算符(例如 &+ 、 &* 等)之外,您还可以使用报告溢出方法(可用于整数)来了解算术运算是否导致溢出,例如此示例:

   let int1 : Int8 = Int8.max   //127
   let int2: Int8 = 50

 //this method provides a boolean flag 
  let (sum1,didOverflow ):(Int8,Bool) = int1.addingReportingOverflow(int2)

  print("sum is \(sum1) and isOverflowing = \(didOverflow)")
//sum is -79 and isOverflowing is true

  let sum = int1 &+ int2 //wont crash for overflows
  let unsafeSum = int1.unsafeAdding(int2) //crashes whenever overflow