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

To specifically answer GreenGirl's original question.

When you write an isolated closure as you have done so in your original example I will admit that yes it does seem a bit odd to have to repeat the type signature inside the closure block and use the in keyword. However in my own projects the main use of this closure syntax is in chained functional style code (map, filter, reduce etc.). Here is an example of what I am talking about from one of my functions from the game logic of the board game 'The Settlers of Catan'.

func extendsPlayersRoad(edge: Edge, playerId: Player.Id) -> Bool {
    return [edge.p1, edge.p2]
        .flatMap{ point -> Vertex? in
            graph.getVertex(point: point)
        }
        .filter{ vertex -> Bool in
            !hasOpponentBuilding(vertex: vertex, playerId: playerId)
        }
        .flatMap{ vertex -> Set<Edge> in
            graph.connectedEdges(vertex: vertex)
        }
        .contains{ edge -> Bool in
            edge.road?.playerId == playerId
        }
}

When seen in this context the placement of the <parameter> -> returnType in within the closure block makes a lot more sense. It wouldn't compose well with chained trailing closure syntax otherwise. Swift's syntax for chained functional code like this is much nicer and clearer than Java8's in my opinion.

6 Likes

Agree with the author. The suggestion the author gives (without the need of the β€˜in’ keyword) is better

Also it seems there is no way to express generic closure.

So you have to use generic function syntax.