Operator overloading in Swift

Sudhanshu Srivastava
1 min readJul 18, 2022

--

Photo by NoWah Bartscher on Unsplash

Operator overloading is a powerful technique available in Swift (and other programming languages) that facilitates you to define your own operator and change the behaviour of any existing operator.

Operators are divided into 3 categories:
Unary {prefix/postfix} (e.g. “++”) that takes only 1 argument
Binary {infix}(e.g. “+”) that takes only 2 arguments
Ternary (e.g. sun_is_up ? wake_up : go_back_to_sleep)

Generally asked interview question on operator overloading is

How you can mimic the functionality of nil-coalescing operator “??” using other symbols / operator?

It can be a surprising question for few. So let’s see what we can do in Swift to achieve what is needed.

Before moving ahead we’ll learn about infix operator.

infix operator in simple terms is a function where the name of the function appears in the middle of two arguments. e.g. +

So “??” is a function that takes 2 arguments and you can use it by mentioning it in the middle of the arguments.

Example

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudhanshu Srivastava
Sudhanshu Srivastava

Written by Sudhanshu Srivastava

I write about what I learn. Swift, Kotlin, Flutter, Social and Life.

No responses yet