Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将值传递给闭包?_Ios_Swift_Block - Fatal编程技术网

Ios 将值传递给闭包?

Ios 将值传递给闭包?,ios,swift,block,Ios,Swift,Block,我想在处理最后一个项目后执行额外的逻辑,但终端显示I始终具有与c相同的值。知道如何传入循环变量吗 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(), {

我想在处理最后一个项目后执行额外的逻辑,但终端显示
I
始终具有与
c
相同的值。知道如何传入循环变量吗

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
            }
        })
    })
}
让c=a.count

对于var i=0;i您需要声明一个变量(不是迭代变量)以获得正确的范围,例如

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

var _i=0的
_i执行闭包时,for循环已经完成,并且
i
=
c
。在for循环中需要一个辅助变量:

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
            }
        })
    })
}
让c=a.count

对于var i=0;i您可以使用捕获列表
[i]
在闭包中,则不需要将其复制到单独的变量。 例如:

设c=5

对于var i=0;iClosure从外部范围捕获变量,因此这段代码应该很好。请提供初始化“c”的位置。如果“c”的值太高,这肯定会达到线程限制。。。
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