Closures and Closure Expressions are two different things

Bit of quick monday morning pedantry., while fun and useful, is perpetuating a subtle conflation of two things, that most Swift programmers have silently adopted, that in turn is probably confusing a lot of beginners.

This function returns a closure:

func return_a_closure() -> () -> (Int) {
  acc = i
  func the_closure() -> Int {
    return ++acc

Even though func was used to define the closure, not { }, it is still a closure, because it’s a function that captures an environment of variables (in this case acc).

The { } syntax alternative to func is called a “closure expression” but it doesn’t make the function returned any more closurey than the example above.

If you already know the difference, it’s natural to drop the word “expression” and just call them closures, and this is what most people writing about Swift are doing. This was inevitable as soon as Apple decided to call them closure expressions, rather than blocks or lambdas or anonymous functions. But this conflation seems to be confusing a lot of people coming to Swift without a background in first-class function and closures. The opening of the closures chapter in the official Swift book makes the difference quite clear, but still the confusion remains.

The bright side is this might be forcing new developers to learn about closures, by throwing them in the terminology deep end. If Apple had stuck with Objective-C’s term, blocks, maybe fewer programmers would be learning about variable capture (plus, was already taken).

What would have been really cool? If Apple had done away with the func keyword altogether, leaving closure expressions assigned to variables as the only way to declare functions. But that would have pushed way too many people out of their comfort zone.

If all this is nonsense-speak to you, try reading this tutorial.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s