Why can't closures have labels and be more readable?

The closure syntax tries to serve a lot of different purposes; I tried to explain some of the historical context in a response to this thread. For your use case, Swift also supports nested named function declarations:

func multiplyByTwoAndThree(a: Int) -> (Int, Int) {
  func multiply(b: Int) -> Int {
    return a * b
  }
  return (multiply(b: 2), multiply(b: 3))
}

and these have all the powers of closures—they can refer to their outer context, and be passed around as function values—but also allow you to use the same syntax as top-level functions and methods, use argument labels, and so on.

As for why function types don't themselves support argument labels, see SE-111 for background; it was a cleanup of the type system and language design around function types and argument labels, to make it so that argument labels are consistently always a part of declaration names like they are in Objective-C. In accepting that proposal, we left the door open to considering allowing labels to appear again as part of declarations involving closures; in the future, we could again allow var multiply: (a: Int, b: Int) -> Int as a declaration of multiply(a:b:) as a variable.

10 Likes