Why is it possible for a Swift function to return a mathematical operator alone?

354 views Asked by At

I'm completely at a loss on how the addTwoNumbers function in the Swift playground code sample below can return "(+)" as a function of type (Int, Int) -> Int and later successfully add the two numbers together by simply calling "addTwoNumbers(2,2)".

I was unable to find an explanation in the Swift documentation as this creative solution seems to be absent there. I've seen StackOverflow answers post similar code out as answers to other questions, but never explained why " = (+)" works. What am I missing?

Please note: I understand operators are functions which are First Class Functions. I also understand the concept of High Order Functions. I shortened the code sample to stay on topic, which is (+).

let addTwoNumbers: (Int, Int) -> Int = (+)
print(addTwoNumbers(5,3)) //8
1

There are 1 answers

0
Gusutafu On

In your example nothing really returns +, what it does is assign the value + (operators are functions and functions can be considered values) to a variable, namely addTwoNumbers.

The type of this variable is (Int, Int) -> Int, i.e. a function of two ints that returns an int. Now functions are a special kind of variable that can take parenthesis as a sort of postfix operator, a bit like normal variables takes a .. If you write the the name addTwoNumbers without parenthesis it refers to the function (which happens to be +), but with them and some operands the function is instead applied, and the value will be whatever the function returns with those arguments.

Note that let addTwoNumbers: (Int, Int) -> Int = (+) is pretty much equivalent to func addTwoNumbers(_ a: Int, _ b: Int) -> Int { return a + b }