“Let me throw you a hand”

If you are making an application that is heavy on math calculations, you may wish to be able to catch errors such as division by zero and integer type overflows before they spread all over the place.

Floating point errors include division by zero, which produces ±infinity, and undefined (NaN) expressions, such as sin(Double.infinity). These fail silently. Integer type operator errors are limited to overflows, which make your code crash loudly.

Swift provides handy integer arithmetic operators permitting overflow; &+,&−, &*, and more informative methods such as addWithOverflow(_,_). I have leveraged these methods to define throwing operators &&+, &&−,&&*, &&/, &&%, and &&?. Usage follows.

 *  Example.swift
// Produces 15.27543444817377
func x() throws -> Double {
  return try (12.5 &&+ 2.3) &&/ (&&?sin(3.1) &&+ &&?atan2(4,3))
// Throws ArithmeticOperationError(.infinity,.division)
func y() throws -> Double {
  let y = try (1.0 &&+ 1.0) &&/ (&&?sin(M_PI_2) &&- 1.0)


Full code ahead.

Hope you found this article useful or interesting 🙂

About Adolfo Rodríguez

iOS Developer at Mokriya