Learn how to create custom operators in Swift.
For example, let’s create a completely new square root operator that works with the check mark emoji.
prefix operator ✔️ prefix func ✔️(num: Double) -> Double { return sqrt(num) } print(✔️25.0) // prints 5.0
In this article, I will show you how you can create your own 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.
Let’s see examples of implementing custom operators for each customizable operator type.
Custom Prefix Operator in Swift
Let’s implement an emoji square root operator, such that you can replace sqrt(25.0)
with ✔️25.0
.
As the ✔️
sign is in front of the number it is operating on, the operator is a prefix operator. With this in mind, let’s implement the custom square root operator and examine the code:
prefix operator ✔️ prefix func ✔️(num: Double) -> Double { return sqrt(num) } print(✔️25.0) // prints 5.0
- In the first line, you let the program know that there is a new prefix operator,
✔️
. - Then you simply create a
prefix func
that defines the behavior of the✔️
operator, which in this case is: return the square root of an argument.
Let’s see a couple of other examples to cover the rest of the operator types:
Custom Infix Operator in Swift
Although you already have a +
operator in Swift, let’s create a new one using an emoji ➕.
A plus sign is placed in between two numbers. Thus the type of the custom addition operator needs to be infix
:
infix operator ➕ func ➕(lhs: Int, rhs: Int) -> Int { return lhs + rhs // regular + operator } print(3 ➕ 6) // prints 9
This operator takes two arguments, lhs
and rhs
(left-hand side and right-hand side respectively), sums them up and returns the result.
Notice how in this case Swift does not require you to use infix
keyword in front of the func ➕
definition.
A Custom Postfix Operator in Swift
A great example of a postfix operator is the factorial operator (!
). For example, the factorial of five is: 5! = 5 * 4 * 3 * 2 * 1 = 120
.
Let’s create a custom factorial operator using the emoji,❗, that computes the factorial of an integer so that you can call it for any integer, for example, like this:5❗
.
Use this factorial
function to compute factorials:
func factorial(_ n: Int) -> Double { return (1...n).map(Double.init).reduce(1.0, *) } factorial(5) // prints 120.0
Now you may implement the factorial operator in a similar fashion to the other examples, by using postfix
keyword this time:
postfix operator ❗ postfix func ❗(num: Int) -> Double { return factorial(num) } print(5❗) // prints 120.0
A Custom Assignment Operator in Swift
Finally, let’s create a new assignment operator, that divides a number by another and updates the original number using emoji ➗
in combination with Swift’s assignment operator (=
)
For example, you want to be able to:
var num = 14.0 num ➗= 2.0 print(num) // prints 7.0
At this point, there is no keyword for a custom assignment operator. Instead, you have to declare a new infix
operator ➗=
(makes sense as it is going to be placed between two numbers). The rest is self-explanatory:
infix operator ➗= func ➗=(lhs: inout Double, rhs: Double) { lhs = lhs / rhs } var num = 14.0 num ➗= 2.0 print(num) // prints 7.0
In case you wonder what lhs: inout Double
means, it means that the left-hand side is a variable whose original value is going to change. Thus the keyword inout
.
Good! Now you have learned how to create completely new custom operators.
Conclusion
Today you learned about Swift custom operators
In Swift, there are five different operators such as the +
operator, which is an infix operator.
You can create your own custom operators in Swift easily.
Thanks for reading. Happy coding!
Further Reading
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.01.10How to Use AI Art Generators—Input Design (Prompt Engineering)
Python2022.12.08How to Get HTML Element (X, Y) Position with JavaScript
Python2022.12.01Double Quotes vs Single Quotes in JavaScript
Favorites2022.11.30ChatGPT—What Is It? How to Use It? (Examples, Tips & More)