How are you handling @MainActor Delegates and Protocols in Swift 6?

This specific warning usually happens because your class is "isolated" to the Main Actor (the UI thread), but the protocol doesn't guarantee that. When you try to assign the delegate, Swift worries that a background thread might try to call those methods, causing a data race.

Here is a concise, punchy Reddit post to get the community's take on the "new" way to handle this.


Title: How are you handling @MainActor Delegates and Protocols in Swift 6?

Post Body:

I'm hitting a wall with the Delegate pattern under strict concurrency.

The Setup: I have a Manager (non-isolated) and a ViewController (isolated to @MainActor). When I try to set the delegate, or call delegate methods, I get isolation mismatch warnings.

The Question: What is the "correct" architectural way to handle this now?

  • Do you mark the Protocol itself as @MainActor?

  • Do you keep the protocol non-isolated and use Task { @MainActor in ... } inside the Manager?

  • Or is it time to ditch delegates for AsyncSequence or Observation?

Curious how everyone is satisfying the compiler without nesting Task blocks everywhere.

I don’t think that the delegate pattern is particularly special from a language perspective. It’s a protocol. That means you have to deal with all of the concurrent implications of using them. There are a lot, and many are conceptual/design issues that previously you could just ignore.

The "Protocol Conformance Isolation Mismatch" of the Swift 6 migration guide goes into a lot of detail on the problem and what options you've got. Unfortunately that document has not be updated to cover isolated conformances, which are new in 6.2. They are a powerful feature that are, in general, very useful for these kinds of problems. Particularly when either the protocol or conforming type are not in your control.

But I'm pretty sure this question is unanswerable without more information. Because there is no "correct solution". It all depends on what constraints these types currently have and what constraints they actually need. Most likely the answer will end up being either "isolate the protocol" or "use an isolated conformance".

2 Likes