Search code examples
swiftinteger-overflow

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


I'm importing some old C code into a swift project, and porting it across to pure swift code.

Some of it does "encryption" wherein it does something like

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

In C this just underflows and wraps around, which is fine for this particular function.

In swift this triggers a fatalError and terminates my program with EXC_BAD_INSTRUCTION because swift by default is designed to catch integer over/underflow.

I'm aware I can turn this checking off at the entire project level by compiling with -Ofast, but I'd really like to just turn off the overflow checking for this one line of code (or perhaps just the specific function itself).

Note: I specifically want to preserve the behaviour of the C function, not just promote things up to Int32 or Int64

This particular term seems really hard to google for.


Update: The answer is the Overflow operators, which are

  • &- for subtraction
  • &+ for addition
  • &* for multiply

I couldn't find them in my previous searching. Oops


Solution

  • You can use addWithOverflow or subtractWithOverflow class method of Int, UInt8 etc types

    E.g. let b = UInt8.subtractWithOverflow(a, 237)