Closures in Swift

Closures are blocks of code that defines functionality in your code. Closures can capture and store references to any constants and variables from the context. Basically, swift handles all of the memory management of capturing. Yet, when building hierarchies of objects and closures you have to be very careful in considering which type that will act as the owner for each given instances. With a clear hierarchy, parent instances will be responsible in retaining their children in which, children instances will be “weak” references, and a lot of memory related problems will be avoided.

@Escaping: When the passing argument defined in outside of the closure and will be executed later this argument must be defined as @escaping. When the execution ends, the scope of the passed closure will exist in the memory till it gets executed. In such, asynchronous functions like waiting API response, or calling Grand Central Dispatch – like doing animation, will cause the @escaping argument to be stored in memory until the animation is done, or api delivers response. In those cases, we must explicitly  define self’s as “weak” properties to avoid memory issues.

@Non-Escaping: When the passing argument is already a in a function, closure executes the argument in the function itself and returns it to back the compiler. In those cases, once the execution ends, the passed closure goes out of scope and have no more existence in memory. (Default one)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s