Swift for C++ Practitioners, Part 7: Closures

submited by
Style Pass
2024-04-29 09:00:05

Throughout this series, I've been using closures in examples without really defining them. Swift closures are a whole lot like C++ lambdas, with a similar design and syntax, and generally the same use cases. This post is going to dig a little deeper into Swift closures to give a better feel for how they work and how to make the best use of them.

defines a local variable hello that stores the closure. The type of hello is () -> String, i.e., a function that takes no parameters.

Swift closures can be provided with parameters in one of two ways: anonymous parameters $0, $1, $2, and so on let you write very short closures for quick one-off operations. For example:

Please only use this shorthand for the smallest closures. Once you get behind a single short expression, it's much better to name your parameters. To do so, list them prior to in within the curly braces. The in separates the declaration part of the closure from its statements. For example, the first case above could instead by written like this:

In fact, prior to the in, you can write a full-fledged parameter list with type annotations, result type, and effect specifiers, if you don't want to leave them up to inference:

Leave a Comment