使 Swift 协议符合 Sendable

问题描述 投票:0回答:1

我们正在尝试通过启用严格的并发检查来为 Swift 6 做好准备。在很大程度上,我了解我们如何解决所产生的警告,但有一个领域我正在努力解决,那就是使用协议抽象时。

例如,解决以下警告最合适的方法是什么?

import Foundation

protocol FooProtocol {
  func foo()
}

struct Foo: FooProtocol {
  func foo() {}
}

struct Bar: Sendable {
  // Stored property 'foo' of 'Sendable'-conforming struct 'Bar' 
  // has non-sendable type 'any FooProtocol'
  let foo: FooProtocol

  init(foo: FooProtocol) {
    self.foo = foo
  }
}

let bar = Bar(foo: Foo())

我们可以通过使

FooProtocol
符合
Sendable
来轻松消除警告:

protocol FooProtocol: Sendable {}

但是我不确定这感觉是否正确。通过添加这个注解,我们是说符合

FooProtocol
的具体类型是Sendable,还是仅仅说里面的函数符合
Sendable

swift concurrency sendable
1个回答
0
投票

如果您使一个协议继承另一个协议,则所有符合类型也必须符合继承的协议。

因此,通过让您的

FooProtocol
继承
Sendable
FooProtocol
的所有符合类型也必须符合
Sendable

© www.soinside.com 2019 - 2024. All rights reserved.