With update to Swift 5.10 I have got many warnings, all saying the same:
warning: passing argument of non-sendable type 'B' outside of actor-isolated context may introduce data races
I took out a few of them out of Apple SDKs to understand it better without any luck. So will appreciate any help on why there is a warning, and maybe where to read more on why it is a warning here? And how to correctly resolve it.
First example is simplified part of SwiftUI view, where a task group is created.
@MainActor
struct Wrapper {
func test() async {
await withTaskGroup(of: Void.self) { group in
for _ in 0..<100 {
group.addTask {
print("Hello, world!")
}
}
await group.waitForAll() // warning: passing argument of non-sendable type 'inout TaskGroup<Void>' outside of main actor-isolated context may introduce data races
}
}
}
I have managed to go await this warning by making this method nonisolated
, yet I do not understand why?
The second example is an actor that uses other non-sendable class:
actor A {
private let b = B()
func prepare() async {
await b.prepare() // warning: passing argument of non-sendable type 'B' outside of actor-isolated context may introduce data races
}
}
final class B {
func prepare() async {
}
}
If I pass isolated A
as parameter to B
, the issue is gone since now prepare
is isolated on an actor, but is that correct way? Or something should be done completely differently here?
Finally, I have top-level execution code where async calls being wrapped in a task, and it also gives data race warning, while I assumed it should be OK since everything is happening in main actor isolation context.
@MainActor
protocol Commands {
func load()
}
final class List {
func load() async {
}
}
@MainActor
struct ErrorHandler {
func task(_ execute: @escaping () async throws -> Void) {
Task {
try! await execute()
}
}
}
struct CommandsImpl: Commands {
let list = List()
let handler = ErrorHandler()
func load() {
handler.task {
await list.load() // warning: passing argument of non-sendable type 'List' outside of main actor-isolated context may introduce data races
}
}
}