What is currying in Swift?
Overview
In simple terms, currying is the technique of modifying the function that takes multiple arguments into a sequence of single argument functions.
We have a function that accepts a number of arguments. We then modify that function to only accept one argument and return a function that accepts the next argument, and so on, until all arguments are satisfied.
Example 1
Let’s understand this with an example. Consider the following simplest function of adding two integers.
func addTwoInts(_ num1: Int, _ num2: Int) -> Int {return num1 + num2}print(addTwoInts(5, 10))
Explanation
In the code above, the function addTwoInts() takes two integers and returns the sum of the passed integers.
We call addTwoInts() function with 5 as num1 and 10 as num2 and we get the result as 15.
Example 2
Now, we define the addTwoInts() function in a different way using the concept of currying.
func curriedAddTwoInts(_ num: Int) -> (Int) -> Int {return { $0 + num }}print(curriedAddTwoInts(5)(10))
Explanation
In the code above, we create a function called curriedAddTwoInts() that takes one integer and returns a function.
We call the curriedAddTwoInts() function with 5 (first argument) as num that returns a function. The returned function is invoked with 10 (second argument) as the parameter.
In this case, both functions addTwoInts() and curriedAddTwoInts() are doing the same task. These two examples demonstrate how a function that accepts numerous parameters at once can always be broken down into a succession or chain of functions that take one argument at a time. This is the currying technique.
Example 3
Consider the following example,
Given a list of integers, we need to add the number 10 to every number in the list.
We can easily achieve this using the map() function.
func curriedAddTwoInts(_ num: Int) -> (Int) -> Int {return { $0 + num }}let ten = curriedAddTwoInts(10)let numbers = [2, 4, 5, 7, 9]print("Original numbers - ", numbers)let newNumbers = numbers.map(ten)print("Modified numbers - ", newNumbers)
Benefits of currying
Some of the benefits of currying are as follows:
- Code reusability.
- Ease of understanding code as complex logic is broken down to multiple functions.