如何捕获变量的块当前值

有没有办法保存变量的当前值以供以后在块中使用?

例如,对于此Playground代码:

import UIKit import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true class testClass { var i = 0 func test() { let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)) * 5) dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.test(self.i) }) i = 3 } func test(i: Int) { print("i: \(i)") } } let a = testClass() a.test() 

有没有办法以我得到输出i: 0而不是i: 3的方式为dispatch_after保存i的当前值?

您可以将任意表达式绑定到捕获列表中的命名值,在创建闭包时计算表达式。 在你的情况下,你会绑定self.i

 dispatch_after(dispatchTime, dispatch_get_main_queue(), { [i = self.i] in self.test(i) }) 

由于您通过捕获的self引用i ,因此您将获得调度时的任何值。 如果要捕获函数开头的值,则需要在更改之前获取本地副本。

  let x = self.i dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.test(x) })