gpt4 book ai didi

ios - 将值传递给闭包?

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:41 25 4
gpt4 key购买 nike

我想在处理完最后一项后执行额外的逻辑,但终端显示 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
}
})
})
}

最佳答案

当你的闭包被执行时,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
}
})
})
}

关于ios - 将值传递给闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31565832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com