Power Tools: Closures & Array Methods
9 min · Swift
Write inline closures and transform arrays with map and filter.
Enemy 1 of 5
This code stores a small piece of code in square, a closure that multiplies a number by itself, then calls it with 6. Press Run to see it print 36.
Why this works
A closure is a small, self-contained block of code you can define right where you need it, without a separate func declaration. The general syntax is { (params) -> ReturnType in expression }: parameters and a return type in parentheses, the in keyword marking where the body starts, then the expression itself. You can assign a closure to a let and call it exactly like any other function. square(6) behaves identically whether square was defined with func or as a closure.
Closures are called that because they can capture ("close over") variables and constants from the surrounding scope, which is part of what makes them so useful for the short, situational logic you hand to functions like .map { } and .filter { } below, instead of writing a whole separate named function for a one-off transformation.