在Swift的Dispatch闭包中修改struct实例变量

tfr*_*377 11 struct grand-central-dispatch swift

我正在使用DEVELOPMENT-SNAPSHOT-2016-06-06-aSwift 的版本.我似乎无法绕过这个问题,我已尝试@noescape在各个地方使用,但我仍然有以下错误:

闭包不能隐式捕获变异的自身参数

为了更好地解释,这是一个简单的例子:

public struct ExampleStruct {
  let connectQueue = dispatch_queue_create("connectQueue", nil)
  var test = 10

  mutating func example() {
    if let connectQueue = self.connectQueue {
      dispatch_sync(connectQueue) {
        self.test = 20 // error happens here
      }
     }
   }
 }
Run Code Online (Sandbox Code Playgroud)

这些Swift二进制文件中的某些东西必须已经改变,现在导致我以前工作的代码中断了.我想避免的一种解决方法是使我的结构体成为一个类,这有助于解决问题.如果还有其他方法,请告诉我.

Kam*_*xom 12

我无法测试它,因为我没有使用的生成与该错误,但我通过捕捉自我敢肯定,明确你能解决这个问题:

dispatch_sync(connectQueue) { [self] in
    self.test = 20
}
Run Code Online (Sandbox Code Playgroud)

编辑:显然它不起作用,也许你可以尝试这个(不是很好tbh):

var copy = self
dispatch_sync(connectQueue) {
    copy.test = 20
}
self = copy
Run Code Online (Sandbox Code Playgroud)

如果您想了解更多关于原因的信息,请参阅负责的Swift提案.

新的调度API使该sync方法@noreturn不需要显式捕获:

connectQueue.sync {
    test = 20
}
Run Code Online (Sandbox Code Playgroud)