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

--

--

Sudhanshu Srivastava

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