ios - Pass value to closure? -
i want logic after last item processed, terminal show i
has same value c
. idea how pass loop variable in?
let c = a.count 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 == c-1 { // stuff come here } }) }) }
you can capture value of i
explicitly capture list [i]
in closure, don't need copy separate variable. example:
let c = 5 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:
0 c 5 1 c 5 2 c 5 3 c 5 4 c 5
Comments
Post a Comment