Adding Custom Operators

Operators are precious things. They are symbols that behave like functions but adopt more natural syntax, for example, 1 + 2 versus addPair(1, 2). Operators allow you to check, change, and combine values using a mathematical notation:

 1 + 2 ​// operator version
 addPair(1, 2) ​// function version

The operator version uses a plus sign between its two numbers. This is called infix form. It’s simple and easy to read. You write the code, just as you’d write an equation. Below it is the functional version, which uses a custom name, and it lists its arguments within parentheses. This form is wordier. It feels more constructed than the operator version. The operator version represents the way you were taught to write this ...

Get Swift Style, 1st Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.