通过价值关闭? [英] Pass value to closure?
本文介绍了通过价值关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在处理完最后一项后做额外的逻辑,但终端显示 i
总是与 c $ c相同的值$ C>。知道如何传递循环变量吗?
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
}
})
})
}
推荐答案
您可以使用捕获列表 [i]显式捕获
i
的值闭包中的
,那么你不需要将它复制到一个单独的变量中。
示例:
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)")
})
})
}
输出:
i 0 c 5
i 1 c 5
i 2 c 5
i 3 c 5
i 4 c 5
这篇关于通过价值关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文