In Swift 4, how can I curry func, or something similar:
func doSomething(a: A, b: B, c: C) {
}
let do_a = doSomething(a: value_a)
let do_ab = do_a(b: value_b)
let result = do_ab(c: value_c)
In JS, we can do:
const sum = x => y => x + y;
// returns a function y => 2 + y
sum (2);
// returns the number 3
sum (2)(1);
I read the answer in here Curry Function in Swift
But I want to ask for the current Swift (Swift 4). And can I avoid to create a generic func?
func curry<A,B,C,D,E>(f: (A, B, C, D) -> E) -> A -> B -> C -> D -> E
This post is very useful: https://robots.thoughtbot.com/introduction-to-function-currying-in-swift
But it's from 2014
Thank you.
You used to be able to do this very easily in Swift 2:
func add(a: Int)(b: Int) -> Int {
return a + b
}
let add3 = add(3) let result = add3(b: 5) // 8
Starting from Swift 3, this is no longer valid syntax.
You'd have to do something like this:
func add(_ a: Int) -> (Int) -> Int {
return { $0 + a }
}
For three parameters, this will be even longer and harder to understand. I recommend you not to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With