Codable, SwiftConcurrency, Swift 6 - Fundamentally incompatible?

Your intuition is right here, and Swift 6 allows you to do exactly this. The feature has the scary name Region Based Isolation, but it's designed to be as invisible as possible to the programmer in service of the intuition you describe above. In other words it should 'just work'.

Once your class instance has been initialised in the background, you can then pass it to its final destination on the @MainActor – by assigning it to a main actor isolated property for example. From that point on, the compiler will enforce it can't leave. (A bit like the Hotel California.)

In effect, it has become @MainActor isolated. No annotations required, the instance inherits the isolation of its host, and the compiler won't permit a data race.

The caveat here is that this doesn't solve your issue of conforming an 'isolated' class to a non isolated protocol. But hopefully what has been conveyed in this thread is that it's quite possible – but not certain – you may not need to.

For example, maybe your situation would require moving (not duplicating) some routines that currently live on your class to now live on your instance hosting @MainActor type. But whatever the situation, I'm sure you'll find plenty of people who are very interested in understanding your problem so that they can either give you a suitable workaround or move the language in a direction that alleviates the issue over the longer term.

6 Likes

Just something I want to highlight - initialization isn't just special, it is incredibly special. There is an enormous amount of subtly and complexity around how initialization and isolation interact. Are the types involved Sendable? Is the initializer non-isolated? Do they have default value expressions? Are the values referenced within the same module? Is it an actor type? This is just off the top of my head.

The compiler bends over backwards to provide a ton of flexibility here. You can pull off a lot stuff that feels like cheating! But it has all been proven safe.

The bad news is because you can pull off a lot of tricky things you can get yourself quite deep into a design before you realize that you have a fundamental design problem.

5 Likes