Currying in Swift — A good way generate similar functions
Sometime, we write some functions have similar meaning or the implementation among them are so similar.
Like we may do this:
func addOne(num: Int) -> Int {
return num + 1
}then when we want to addTwo function due to timing issue we do it like:
func addTwo(num: Int) -> Int {
return num + 2
}Is there a way to simplify it or make it easier? Yes, use Currying
func addTo(_ number: Int) -> (Int) -> Int {
return {
num in
return num + number
}
}After we have this function with a closure return we can make this copy and paste easier. We can just convert addOne and addTwo function above into the following:
let addOne = addTo(1)
let addTwo = addTo(2)func test(){
print("\(addOne(1)") //will print 2 which is 1 + 1
print("\(addTwo(1)") //will print 3 which is 1 + 2
}
With this currying we massively generate a lot of similar functions without worrying too much of code duplication, I will also help us with code maintenance. When requirement changes, we don’t have to change those similar implementation in each the how we did in addOne and addTwo we just simply modify the addTo function.