How to “ObjectContext” with Swift 6 concurrency

After reading about a similar thought process (tying a non-sendable to an isolation via a stored isolated any Actor value) in another post I kept thinking about this some more.

The language makes it so easy to slap global actor attributes onto things to isolate non-sendable parts together, but so hard for use cases where there is no meaningful "statically known" isolation context (eg: server-side processing)

So, just throwing out ideas here, what if we had:

// automagically tie this to the #isolation of its initializer
// and somehow keep a reference to the actor
@inheritsIsolation
final class Context {
    // async function is tied to the actor captured by the initalizer
    func fetch<M: Entity>(_ type: M.Type = M.self, byId id: M.ID) async throws -> M? { ... }
}

func myOperation() {
    // provide "epemeral" actor isolation
    try await withIsolation { 
        // tied to the current #isolation
        let context = Context()

        // should then work, because all isolated to same actor (right?)
        let a = async let context.fetch(A.self, byId: "aaa") 
        let b = async let context.fetch(B.self, byId: "bbb")
        
        try await doSomeWork(a, b)
    }
}

I'll gladly take an isolated ... = #isolation parameter in the constructor that can be stored in a let and understood by the compiler as well of course ; )

3 Likes