CODEX
Swift Custom Operators
Learn how to create your own operators in Swift.
Published in
4 min readMar 8, 2021
Swift lets you create your own customizable operators.
In this article, I will show you how you can easily create your own custom operators in Swift.
Operator Types in Swift
There are five main types of operators in Swift. All of the operators fall in one of these categories:
- Infix Operator — Use between two variables for example
1 + 2
- Prefix Operator—Use before a value, for example
!true
- Postfix Operator—Use after a value, for example
4!
(!
means factorial. For example, the factorial of 4 is4! = 4 * 3 * 2 * 1 = 24
) - Assignment Operator—Update an original value by performing an operation on it. E.g.
num += 1
incrementsnum
by one. - Ternary Operator—An operator of two symbols between three expressions. Swift has only one ternary operator called ternary conditional operator (
condition ? true_expression : false_expression
). This is the only non-customizable operator type on this list!
Every operator type above (except the ternary operator) is customizable. This means you can create a new operator for your needs.