Swift 2.1 中的块存储变量
Posted
技术标签:
【中文标题】Swift 2.1 中的块存储变量【英文标题】:Block stored var in Swift 2.1 【发布时间】:2016-05-11 15:12:46 【问题描述】:所以,我正在做一个异步查询,它返回多个 Worker 对象,每个 Worker 都与 WorkerPeriod 有关系,我使用这个关系来进行查询,问题是,查询是异步的,当它返回时从网络服务,workerIndex 搞砸了
workerQuery.whereKey("construction", equalTo: currentConstruction).findObjectsInBackgroundWithBlock( (unsafeWorkers, error) -> Void in
guard let workers = unsafeWorkers as? [Worker] where error == nil && workers.count == 0 else
return
for var workerIndex = 0; workerIndex < workers.count; workerIndex++
let currentWorker = workers[workerIndex]
if let periodQuery = WorkerPeriod.query()
periodQuery.whereKey("worker", equalTo: currentWorker)
let weakWorkerIndex = workerIndex
print("weakWorkerIndex = \(weakWorkerIndex) worker \(workerIndex)")
periodQuery.findObjectsInBackgroundWithBlock( (unsafeWorkerPeriod, error) -> Void in
guard let workerPeriods = unsafeWorkerPeriod as? [WorkerPeriod] where error == nil && workerPeriods.count != 0 else
return
print("block weakWorkerIndex = \(weakWorkerIndex) workerIndex \(workerIndex)")
.
.
)
我尝试创建一个“weakWorkerIndex”作为让我们在 Objective-C 中使用 __block 变量保存值的方法,但这不起作用,块交互只是忽略了值,如您所见在输出中:
weakWorkerIndex = 0 worker 0 weakWorkerIndex = 1 worker 1 block weakWorkerIndex = 0 workerIndex 2 block weakWorkerIndex = 0 workerIndex 2 block weakWorkerIndex = 0 workerIndex 2
顺便说一句:我删除了所有不必要的代码以简化阅读。
【问题讨论】:
【参考方案1】:在完成处理程序中,您需要确保workerIndex
将被捕获按值,例如:
for var workerIndex = 0; workerIndex < 10; workerIndex++
fooAsync [workerIndex] in
print("\(workerIndex)")
见斯威夫特Capture Lists
【讨论】:
以上是关于Swift 2.1 中的块存储变量的主要内容,如果未能解决你的问题,请参考以下文章