Translation framework use in Swift 6

I’m trying to integrate Apple’s Translation framework in a Swift 6 project with Approachable Concurrency enabled.

I’m following the code here: https://developer.apple.com/documentation/translation/translating-text-within-your-app#Offer-a-custom-translation

And, specifically, inside the following code

.translationTask(configuration) { session in
    do {
        // Use the session the task provides to translate the text.
        let response = try await session.translate(sourceText)


        // Update the view with the translated result.
        targetText = response.targetText
    } catch {
        // Handle any errors.
    }
}

On the try await session.translate(…) line, the compiler complains that “Sending ‘session’ risks causing data races”.

Extended error message:

Sending main actor-isolated 'session' to @concurrent instance method 'translate' risks causing data races between @concurrent and main actor-isolated uses

I’ve downloaded Apple’s sample code (at the top of linked webpage), it compiles fine as-is on Xcode 26.4, but fails with the same error as soon as I switch the Swift Language Mode to Swift 6 in the project.

How can I fix this?

Did you try to wrap the code with a main actor task, as shown below:

.translationTask(configuration) { session in
    Task { @MainActor in
        do {
            // Use the session the task provides to translate the text.
            let response = try await session.translate(sourceText)
            // Update the view with the translated result.
            targetText = response.targetText
        } catch {
            // Handle any errors.
        }
    }
}

This gives the "main actor-isolated 'session'" a main actor context, and so should calm down the error, while translate will still run in the background because it's a "@concurrent instance method".

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Translation framework use in Swift 6
 
 
Q