Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: What is the difference between 'Currying' and the function that return a function?

//  function 1------- Currying   
    func increment (incrementBy x: Int)(y: Int) -> Int {
       return x + y
    }

//  function 2------- The function that return a function
    func increment(incrementBy x: Int) -> ((Int) ->Int){
       func incrementFunc(y: Int){
           return x + y
       }
    }

Do that two functions do the same thing , don't they? And I can use them in a same way. Like this:

let incrementFunc = increment(incrementBy: 10)
var number = 10
number = incrementFunc(number)

So, I am confused, what is the difference of them? What is the advantages of each way?

like image 253
Erum Huang Avatar asked Mar 14 '23 13:03

Erum Huang


1 Answers

The first example you have is "syntactic sugar" for the second one, in a similar way that [Int] is shorthand for Array<Int>. They mean the same thing and act the same way.

However, I should point out that this syntactic sugar is going away soon. This proposal, written by a Swift compiler engineer and accepted by the Swift development team, says that the shorthand currying syntax will no longer be a part of the language. Instead, all currying will be done the way your second example is written.

like image 58
erdekhayser Avatar answered Apr 24 '23 22:04

erdekhayser