在Swift中的Dispatch闭包中修改结构实例变量 [英] Modifying struct instance variables within a Dispatch closure in Swift

查看:222
本文介绍了在Swift中的Dispatch闭包中修改结构实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift的DEVELOPMENT-SNAPSHOT-2016-06-06-a版本.我似乎无法解决这个问题,我已经尝试在不同的地方使用@noescape,但是仍然出现以下错误:

I'm using the DEVELOPMENT-SNAPSHOT-2016-06-06-a version of Swift. I cannot seem to get around this issue, I've tried using @noescape in various places, but I still have the following error:

关闭无法隐式捕获变异的自身参数

Closure cannot implicitly capture a mutating self parameter

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

To better explain, here is a simple example:

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
      }
     }
   }
 }

这些Swift二进制文件中的某些内容必须已经更改,这现在导致我之前的工作代码损坏了.我要避免的一种解决方法是将struct设置为类,这确实有助于解决问题.让我知道是否还有另一种方法.

Something must have changed in these Swift binaries that is now causing my previously working code to break. A workaround I want to avoid is making my struct a class, which does help in fixing the issue. Let me know if there is another way.

推荐答案

我无法对其进行测试,因为我没有使用带有该错误的版本,但是我很确定通过明确捕获自身 您可以修复它:

I cannot test it, because I'm not using a build with that error, but I'm pretty sure by capturing self explicitly you can fix it:

dispatch_sync(connectQueue) { [self] in
    self.test = 20
}

显然它不起作用,也许您可​​以尝试一下(不是很好),

Apparently it doesn't work, maybe you can try this (not very nice tbh):

var copy = self
dispatch_sync(connectQueue) {
    copy.test = 20
}
self = copy

如果您想详细了解原因,请此处负责任的Swift提案.

If you want to read more on why, here is the responsible Swift proposal.

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

The new dispatch API makes the sync method @noreturn so you wouldn't need the explicit capture:

connectQueue.sync {
    test = 20
}

这篇关于在Swift中的Dispatch闭包中修改结构实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆