我有一个如下声明的演员协议:
protocol MyActorProtocol: Actor {
func foo()
}
有一个符合协议的参与者:
actor MyImplementation1: MyActorProtocol {
func foo() {}
}
现在我需要添加一个代理:
actor MyImplementation1Proxy: MyActorProtocol {
let impl: MyActorProtocol
init(impl: MyActorProtocol) {
self.impl = impl
}
func foo() {
// Error-1: Call to actor-isolated instance method 'foo()' in a synchronous actor-isolated context
// impl.foo()
// Error-2. 'await' in a function that does not support concurrency
// await impl.foo()
// Success-3. only this passes the compiler check
Task { await impl.foo() }
}
}
我想了解这些点:
- 为什么参与者协议可以在没有显式
nonisolated
关键字的情况下声明非Inbox方法? - 假设有可能有非Inbox方法,那么为什么我的代码中会有
Error-1
个呢? - 鉴于
MyImplementation1Proxy
也符合MyActorProtocol
,并且MyImplementation1.foo
必须在Task
中被调用(无论出于何种原因),那么感觉MyImplementation1.foo
是"一种Jacobc",所以MyImplementation1Proxy.foo
也应该有这种"一种Jacobc上下文",那么为什么我有Error-2
呢? - 从
Error-2
看起来该方法只是"非执行者",但当我试图引入非执行者实现时,得到了Call to actor-isolated instance method 'foo()' in a synchronous nonisolated context
,这很公平,但再次导致问题1:
class MyImplementation2 {
let impl: MyActorProtocol
init(impl: MyActorProtocol) {
self.impl = impl
}
func bar() {
impl.foo()
}
}
提前感谢.