How to share isolation between two actors?

In the following example, I want to share isolation between Foo and it's instance of Bar. (Other instances of Foo would still be in different isolation domains, other actors would also be able to have a Bar child that they share their isolation with, all separately from each other.)

actor Foo {
  private let bar = Bar()
  func foo() {
    bar.bar() // <- normally this needs an await, making foo() async, I want to avoid this
  }
}

actor Bar {
  func bar() {
    // Some synchronous code
  }
}

Hi @Cyberbeni, I don't think Swift currently has the tools to statically guarantee this, though I would love if someday there were such tools.

The closest you can get today is to set Foo's executor to be Bar's executor, and then assume isolation:

actor Foo {
  private let bar = Bar()
  func foo() {
    bar.assumeIsolated {
      $0.bar()  // No 'await'
    }
  }
  nonisolated var unownedExecutor: UnownedSerialExecutor {
    bar.unownedExecutor
  }
}

actor Bar {
  func bar() {}
}

This is of course going outside the purview of the Swift compiler, and so you now have the responsibility to make sure everything is legit. If someday in the future you removed the unownedExecutor then you would get a crash in assumeIsolated.

9 Likes

Sorry, I missed that you want shared isolation only for certain instance.

Deleted

Or, if you want static guarantee and own both Foo and Bar, you could make a global actor and isolate the two to that actor.