I've been working with Swift Concurrency a good bit for about 6 months now and keep bumping into where I need to bridge synchronously between it and other nonisolated system frameworks. I'm curious if there are recommended patterns for this type of interaction.
Consider this scenario:
- I have a
@MainActor
isolated class that I'm using in my UI and would like to make itCodable
. - As soon as you add that requirement, the
init(from decoder: Decoder)
andencode(to encoder Encoder)
must each be nonisolated, synchronous calls, which as far as I can tell means that I need an inner lock (NSLock
or similar) to guard access to the state of the class. - Despite the claim made elsewhere in the forums it is not as simple as adding the
async
keyword to these methods because it changes their signature.
While I agree it is the right thing to encode/decode in the background off the main thread, adding locks every time I need to bridge feels contrary to the spirit of Swift Concurrency.
What am I missing?