Pass value to closure?

ⅰ亾dé卋堺 提交于 2019-12-29 08:42:51

问题


I want to do extra logic after last item was processed, but terminal show that i has always the same value as c. Any idea how to pass the loop variable in?

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
            }
        })
    })
}

回答1:


You can capture the value of i explicitly with a capture list [i] in the closure, then you don't 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



回答2:


By the time your closure is executed, the for loop has already finished and i = c. You need an auxiliary variable inside the for loop:

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
            }
        })
    })
}



回答3:


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

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


来源:https://stackoverflow.com/questions/31565832/pass-value-to-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!