Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you capture multiple arguments weakly in a Swift closure?

Is there a way to capture multiple arguments weakly in a swift closure? I know this is the syntax to capture one argument weakly:

{ [weak arg]     arg.doSomething() } 

How can I do this for two objects that I wish to capture weakly?

like image 924
phoganuci Avatar asked Jan 18 '15 22:01

phoganuci


People also ask

Does closure capture values in Swift?

A closure can capture constants and variables from the surrounding context in which it's defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.

How do closures capture references to variables by default?

In Swift, closures capture the variables they reference: variables declared outside of the closure but that you use inside the closure are retained by the closure by default, to ensure they are still alive when the closure is executed.

What is closure capture in Swift?

Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables.

How many types of closures are there in Swift?

As shown in the above table, there are three types of closures in Swift, namely global functions, nested functions, and closure expressions. They differ in several aspects, including their use scopes, their names, and whether they capture values, which will be discussed more in a later section.


1 Answers

From Expressions in "The Swift Programming Language" (emphasis added):

Closure Expression
...
A closure expression can explicitly specify the values that it captures from the surrounding scope using a capture list. A capture list is written as a comma separated list surrounded by square brackets, before the list of parameters. If you use a capture list, you must also use the in keyword, even if you omit the parameter names, parameter types, and return type.

Example:

{     [weak arg1, weak arg2] in      // ... } 
like image 110
Martin R Avatar answered Sep 25 '22 00:09

Martin R