3

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.

tuledev
  • 10,177
  • 4
  • 29
  • 49

1 Answers1

3

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313