A swift impression on the Swift Tour (3) Functions and Closures

The Swift language has a function signature that is very different from JS. Apart from that, however, the concept and usage of functions and closures is quite familiar to a JS developer who’s used to passing callbacks and writing closures.

Let’s have a look at an illustrative function signature:

The first obvious thing: to declare a function in Swift, we use func instead of function.

Then comes the most confusing part: for each parameter in the function signature, there could be two names before the type. The first one is also called the label of the parameter, which is used when calling the function (as is the case with param1 in the example above). The second one is the name of the parameter, which is to be used inside the function body when referencing the parameter.

When the label in the signature is an underscore _, it means you can simply pass in the parameter value without using a label (as is the case with param2 in the example above). When there’s only one name/label for a parameter (as is the case with param3), this one is to be used both inside the function body and when calling the function.

Functions in Swift is a first-class type, which means any functional programming techniques, such as passing a function as a parameter or returning a function in another function, are all free to use. Thus there are also closures in Swift which can be used similarly as in JS:

(1) Function(s) inside another function. Inner function has access to variables in the outer function.

(2) Returning a function. Note how the returning type is written as an anonymous function signature, with the parameter type in parentheses and an arrow to the return type, all wrapped in another pair of parentheses.

(3) Passing a function as a parameter. Note how the parameter type is written as an anonymous function signature after the parameter label/name, with the parameter type in parentheses and an arrow to the return type.

There is also a peculiar looking way of writing anonymous closures: wrapping the anonymous signature together with the code body in a pair of curly braces with a keyword in denoting the boundary between the signature and the code body.

Going one step further with this curly braces…in expression, we can save the parentheses and return type by writing everything in one line:

Lastly, by accessing parameters by index ($0, $1, etc.), in can also be omitted. And if this very short closure is the only parameter passed in a function, the parentheses can also be omitted, leaving only the curly braces.