Closures and memory management

As we mentioned, a closure closes over the variables and constants it refers from the enclosing context. Now, if the closure is executed synchronously since the caller is blocked waiting for it to return, the closure may safely assume all variables and constants from the enclosing context still exist. On the contrary, when a closure is executed asynchronously, that is, without blocking the caller, there is no such guarantee, and it may happen that the closure is executed when the original enclosing context no longer exists. To ensure, then, that the variables and constants the closure uses outlive the enclosing context, Swift closures are able to capture those variables and constants:

import Dispatchstruct Book ...

Get Hands-On Design Patterns with Swift 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.