Swift Integer Overflow

November 19, 2015

Swift integer types don't allow integer overflows (without some help)

In Swift, this crashes:

var someValue: UInt8 = 255
someValue++
// crashes

Swift's integer types provide an addWithOverflow(lhs,rhs) method.

public static func addWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool)

Here's a quick example:

var someValue: UInt8 = 255
let result = UInt8.addWithOverflow(someValue, 1)
// tuple (0, overflow true)

someValue = result.0
// someValue is 0

The returned tuple contains two values

  • unnamed result value (access with .0)
  • overflow flag indicating if the operation caused an overflow (access with .1 or .overflow)

Subtraction also works

var someValue: UInt8 = 0
result = UInt8.subtractWithOverflow(someValue, 1)
// tuple (255, overflow true)

In summary, Swift provides overflow methods (addition, subtraction, multiplication, division, remainder) for all integer sizes, signed and unsigned. See the IntegerArithmeticType protocol for additional details.