Page 1

Resolving Leaky Closures in Swift

Closures are self-contained blocks of functionality that can be passed around and used in your code. They are similar to blocks in C and Objective-C and lambda functions in other programming languages. Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Closures is a powerful feature in Swift, but it does demand caution in some cases. Classes and Closures are both reference types. Because a closure can capture values from its surrounding scope, a closure can create a reference cycle.

Defining a Capture List: The references a Closure holds to reference types are strong by default. We can change this behavior by defining a capture list. The capture list determines how values used inside the closure should be captured.


Weak Capturing: A weak reference type keeps a weak reference to the instance it references. This means that the reference to the instance will not be accounted for by the ARC. A weak instance is deallocated if there exists no other strong reference to the instance.

Unowned Capturing: Unowned references are similar to weak references in that they don’t keep a strong reference to the instance they are referencing. The difference is unowned reference is always expected to have a value.

For more details visit us at: Synsoft Global 403/404, Airen Heights, Scheme 54, A. B. Road, Indore 452010 (MP), India Contact No: +91 731 6612120

Profile for Synsoft Global

Resolving Leaky Closures in Swift - Synsoft Global  

Closures is a powerful feature in Swift, but it does demand caution in some cases. Classes and Closures are both reference types. Because a...

Resolving Leaky Closures in Swift - Synsoft Global  

Closures is a powerful feature in Swift, but it does demand caution in some cases. Classes and Closures are both reference types. Because a...

Advertisement