Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Create an Operator in Swift

Artturi Jalli
Better Programming
Published in
4 min readJul 14, 2021

--

Remote control
Photo by Clayton Robbins on Unsplash.

Custom operators are a heated topic among iOS developers. Some people think they’re a bad idea, whereas others love them.

Today, I’m going to show you the basics of creating your own operators. You will learn about the five operator types in Swift and how to create custom operators from them.

For example, you are going to learn how to compute a factorial using an emoji:

5❗

Operator Types in Swift

There are five types of operators in Swift:

  • Infix operator — An operator between two values (e.g. 10 + 5).
  • Prefix operator — An operator before a value (e.g. !true).
  • Postfix operator — Occurs after a value (e.g. a factorial 4!).
  • Assignment operator — An operator that updates the value (e.g. num += 1).
  • Ternary operator — An operator with two symbols with three expressions (e.g. condition ? true_expression : false_expression).

In Swift, every operator type except the ternary operator is customizable. This means you can create a new custom operator.

Let’s see some examples.

How To Create a Custom Prefix Operator

Let’s implement an emoji square root operator so that you can replace sqrt(25.0) with ✔️25.0.

Because the ✔️ occurs before the number, the operator type is a prefix operator.

Let’s implement a custom square root operator:

prefix operator ✔️prefix func ✔️(num: Double) -> Double {
return sqrt(num)
}
print(✔️36.0)

Output:

6.0

To understand what’s going on, let’s inspect the code:

  • On the first line, you define a new prefix operator.
  • Then you create a prefix func that defines the behavior of the new ✔️ operator. In this case, it takes the square root of the number argument and returns the result.

--

--

No responses yet