Closures in Other Languages

It may be helpful to see closures in a broader context. A closure itself is relatively the same in all languages. However, Swift provides extra-special syntax for closures, which makes their implementation a bit different. In JavaScript you can create a closure by writing a function within another function. That inner function does not exist outside the outer function and therefore is “enclosed” (hence the name closure) in the outer function. The outer function can then return the inner function and make it available to all. Now the outer function has finished running, and all of its local variables should be dumped. But they aren’t because the inner function is now available globally and still has references to the ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.