2

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
Mark E.
  • 106
  • 7
  • Simpler please @Carcigenicate. Does wrapping the + in parenthesis make it an object? And therefore by calling it with two arguments it becomes the equivalent of 2 + 2? – Mark E. Sep 17 '17 at 05:00
  • @Carcigenicate: A comment from https://math.stackexchange.com/questions/168378/operator-vs-function, states "all operators are functions". So when a function returns an operator (in this case (+) which is also a function), is it safe to assume the only way to call it is via the add(2,2) just like one would print("hello")? In other words, we're calling the + function which takes two arguments, but instead of typing +(2,2), we must type add(2,2) according to the code sample provided? – Mark E. Sep 17 '17 at 05:22
  • My example and question was tailored to the Swift language in the Higher Order Function realm, however your answer gives me some direction to better understand the concept in any language. – Mark E. Sep 17 '17 at 05:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/154607/discussion-between-mark-e-and-carcigenicate). – Mark E. Sep 17 '17 at 05:31

1 Answers1

0

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 }

Gusutafu
  • 745
  • 6
  • 17