Saturday, August 23, 2014

Swift Function Currying

Russ Bishop:

Now forget all that stuff we just discussed because Swift supports automatic function currying. Just separate the parameters inside their own parens and you’re done:

func takeFive<T:IntegerArithmeticType>(a:T)(b:T)(c:T)(d:T)(e:T) -> T {
    return a + b + c + d + e
}

[…]

A caller might ask us for a function that runs queries against a certain database. We can use a curried function (possibly private) that takes connection info as its first parameter, followed by query information as its second; the caller gets back a curried function that takes only the query parameters. The caller can then use this returned function without ever being aware of the details. We don’t have to create queue or thread specific ambient context information to track some sort of “current” connection. The storage lifetime of the connection information is tied to the lifetime of the closure’s environment. When the closure goes away, so too will the saved context. This also lets us have multiple active connections or pass them between queues and threads. In short, we can hide the details without jumping through any hoops or writing boilerplate objects just to carry some state data around.

Comments RSS · Twitter

Leave a Comment