Swift — Tricky Interview Question

Vaibhav Vats
2 min readJul 27, 2022

--

Write a generic function that can add two Integers or append two Strings. For example :
customAdd(2, 3) -> 5

customAdd(“Vai”, ”bhav”) -> Vaibhav

It already happens with + operator. But the question is to make a generic function out of it.

How I first thought of doing it —

But How could It be right. T doesn’t know that it will receive only string or integer it could even receive my custom object and how is it supposed to add that.

I even tried confirming my T to the Numeric and String protocol but that didn't work either.

Stop scrolling any further for a minute and think of solution.

Solution —

+ is a binary operator that is already available with String, Int, Double and more.

Now doing a + b It knows, whether to redirect to integer or a string implementation of + operator.

--

--