Swift Concurrency and synchronous, nonisolated infrastructure?

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 it Codable.
  • As soon as you add that requirement, the init(from decoder: Decoder) and encode(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?

Is there a particular reason you're making a SwiftUI View codable? There is a @SceneStorage and a @AppStorage wrapper you can use to persist properties of a view to storage or NSUserActivity. Why make an entire View Codable?

Swift Concurrency and synchronous, nonisolated infrastructure?
 
 
Q