Pass value to close?

I want to make additional logic after processing the last element, but the terminal shows that i always has the same value as c . Any idea how to pass the loop variable to?

 let c = a.count for var i=0; i<c; i++ { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { // .. dispatch_async(dispatch_get_main_queue(), { println("i \(i) c \(c)") if i == c-1 { // extra stuff would come here } }) }) } 
+5
source share
3 answers

You can explicitly commit the value of i using the capture list [i] in the close, then you do not need to copy it to a separate variable. Example:

 let c = 5 for var i=0; i<c; i++ { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { [i] in // <===== Capture list dispatch_async(dispatch_get_main_queue(), { println("i \(i) c \(c)") }) }) } 

Output:

  i 0 c 5
 i 1 c 5
 i 2 c 5
 i 3 c 5
 i 4 c 5
+6
source

By the time your close is complete, the for loop is already complete and i = c . Inside the for loop you need an auxiliary variable:

 let c = a.count for var i=0; i<c; i++ { let k = i dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { // .. dispatch_async(dispatch_get_main_queue(), { println("k \(k) c \(c)") if k == c-1 { // extra stuff would come here } }) }) } 
+6
source

You need to declare a variable (not an iteration variable) to get the correct scope, e.g.

 for var _i=0; _i<c; _i++ { let i = _i dispatch_async(... 
+2
source

All Articles