swift - 在 'self' 闭包中捕获 `@Sendable`

标签 swift closures task self sendable

我的应用使用以下带有 IBAction 的 View Controller 。
当某个按钮触发操作时,该按钮将被禁用,并启动一些后台处理。
当后台处理完成后,按钮将再次启用,这必须在主线程上完成。

final class DebugViewController: UIViewController {
  button.isEnabled = false
  // …
  @IBAction func action(_ sender: Any) {
    // …
    Task {
      // some background processing
      DispatchQueue.main.async {
        self.button.isEnabled = true
      }
    }
    // …
  }
}

在构建期间,语句 self.button.isEnabled = true 中会显示以下警告:

Capture of 'self' with non-sendable type 'DebugViewController' in a `@Sendable` closure  

我可以通过将 DebugViewController 声明为来避免此警告

final class DebugViewController: UIViewController, @unchecked Sendable {  

但是,当我分析而不是构建代码时,我现在在这一行收到以下错误:

Redundant conformance of 'DebugViewController' to protocol 'Sendable'  

因此我有点困惑:

  • 每个 UIViewController Sendable 是否如“冗余一致性”错误所示?
  • 如果是这样,为什么我会收到 DebugViewController 不可发送的警告?
  • 如果 UIViewController 不可发送,为什么我会收到“冗余一致性”错误?

最终,如何正确地做到这一点?

最佳答案

这显然是 Xcode 13.3 Beta 2 中的一个错误。在发布的版本 13.3 (13E113) 中,没有显示警告。

关于swift - 在 'self' 闭包中捕获 `@Sendable`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71481775/

相关文章:

java - 捕获局部变量 .isSynthetic() 的 Lambda 字段返回 false

programming-languages - 词法范围是如何实现的?

c# - 带有外部参数的 Task.Run 循环由循环更改

ios - 使用系统字体创建 SKLabelNode(UIFont 到字体名称)

swift - 实现可散列和重载运算符的协议(protocol)

ios - Swift 中与 DispatchQueue 同步处理

java - 了解 Spark 的闭包及其序列化

python - 多个 Python 进程缓慢

c# - 如何在不自动降级到同步模式的情况下调用异步方法?

ios - 不能在 drawRect 中使用颜色透明度