Advanced Operator- Custom Operator

Inventor of your operator

Kishore Premkumar
Jun 26, 2020 · 5 min read

In case you miss the advanced operator- bitwise click here.

When you define your own structures, classes, and enumerations, it can be useful to provide your own implementations of the standard Swift operators for these custom types. Swift makes it easy to provide tailored implementations of these operators and to determine exactly what their behavior should be for each type you create.

You’re not limited to the predefined operators. Swift gives you the freedom to define your own custom infix, prefix, postfix, and assignment operators, with custom precedence and associativity values. These operators can be used and adopted in your code like any of the predefined operators, and you can even extend existing types to support the custom operators you define.

Operator methods

Classes and structures can provide their implementations of existing operators. This is known as overloading the existing operators.

The below example shows how to implement the arithmetic addition operator (+) for a custom structure.

The arithmetic addition operator is a binary operator (a binary operation or dyadic operation is a calculation that combines two elements (operands) to produce another element) and is said to be infix because it appears in between those two targets.

Infix operator overloading

In the above program, defines a class which is the name of the AxisPoints which contains two properties xAxis, yAxis. The operator method is defined as a type method on AxisPoints, with a method name that matches the operator to be overloaded (+). The type method is defined in an extension of AxisPointsrather than in the main class declaration of AxisPoint .

The arithmetic addition operator is a binary operator, this operator method takes two input parameters of type AxisPointsand returns a single output value, also of type AxisPoints.

operator method must be in a static form.

In this implementation, the input parameters are named leftSide and rightSide to represent the AxisPoint instances that will be on the left side and right side of the + operator ( axisPointOne + axisPointTwo). The method returns a new AxisPoints instances, whose xAxis and yAxis properties are initialized with the sum of the xAxis and yAxis properties from the two AxisPoint instances ( axisPointOne + axisPointTwo)that are added together.

Output of the above program is,

20 40

Postfix and prefix operator

Classes and structures can also provide implementations of the standard unary operators. Unary operators operate on a single target. They are prefix if they precede their target (such as -operands) and postfix operators if they follow their target (such as operands!).

You implement a prefix or postfix unary operator by writing the prefix or postfix modifier before the func keyword.

In the above program, implements the unary minus operator ( -axisPointsValues) for AxisPoints instances. The unary minus operator is a prefix operator, and so this method has to be qualified with the prefix modifier.

The unary minus operator converts negative numbers into positive numbers and positive numbers into negative numbers.

This operator method takes one input parameters of type AxisPointsand returns a single output value, also of type AxisPoints.

Equivalence Operators

Equivalence operators are equal to operator ( ==) and not equal to operator ( !=).

You provide an implementation of the == or != operator in the same way as you implement other infix operators.

In the above program, implements an == and != operator to check whether two AxisPoints instances have equivalent values. It makes sense to consider “equal” as meaning “both instances have the same xAxis values and yAxis values”, else “not equal”.

Custom Operators

You can declare and implement your custom operators in addition to the standard operators provided by Swift. There are three steps to declare custom operators.

  • Name your operator
  • Choose a type
  • Assign precedence and associativity

Name your operator

you have to pick a character for your operator. Custom operators can begin with one of the ASCII characters /, =, -, +, !, *, %, <, >, &, |, ^, or ~, or with one of the Unicode characters. This gives you a broad range of possible characters.

Choosing a Type

  • Binary operator are infix because it combines two elements to produce another element. (e.g:- 1+1)
  • Unary operators involving a single target and are defined either as postfix (i++) or prefix (++i).
  • Ternary operators operate on three targets. In Swift, the conditional operator is the only Ternary operator, for example a ? b : c.

Assigning Precedence and Associativity

Because operators are defined globally, you need to choose the associativity and precedence of your custom operator with care.

Operator precedence gives some operators higher priority than others; these operators are applied first.

Operator associativity defines how operators of the same precedence are grouped — either grouped from the left, or grouped from the right.

In the above example, the answer is not 10 actual answer is 8. Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the divided operator (%) and the multiplication operator (*) have a higher precedence than the addition operator (+). As a result, they are both evaluated before the addition is considered.

you also need to consider their associativity. Remainder and multiplication both associate with the expression to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left.

Example for custom operator

New operators are declared at a global level using the operator keyword, and are marked with the prefix, infix or postfix modifiers

Custom Infix operator

In the above program, defines a new custom infix operator called +-, which belongs to the precedence group AdditionPrecedence .

This operator adds together the xAxis values of two axisPointsValues, and subtracts the yAxis value of the second axisPointsValues from the first. Because it is, in essence, an “additive” operator, it has been given the same precedence group as additive infix operators such as + and -.

For more information about precedence groups and to see the syntax for defining your operators and precedence groups, see Operator Declaration.

Custom prefix operator

In the above program, defines a new prefix operator called ++++. This operator does not have an existing meaning in Swift, and so it is given its custom meaning. ++++ is treated as a new “prefix doubling” operator. It doubles the xAxis and yAxis values of a AxisPoints instance, by adding the values itself with the addition assignment operator.

You do not specify a precedence when defining a prefix or postfix operator. However, if you apply both a prefix and a postfix operator to the same operand, the postfix operator is applied first.

The Startup

Get smarter at building your thing. Join The Startup’s +788K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Kishore Premkumar

Written by

iOS Developer intern @ivymobility

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store