The same problem also arises when not dealing with Array:
class File {
func read() -> String { "" }
}
func someFunction(
file: File
) async throws {
await withTaskGroup(of: Void.self) { group in
group.addTask { // same error as before
let c = file.read()
print(c)
}
}
}
Neither will the following trick work:
func someFunction(
file: sending File
) async throws {
func helper(_ file: sending File, _ group: inout TaskGroup<Void>) {
group.addTask {
let c = file.read()
print(c)
}
}
await withTaskGroup(of: Void.self) { group in
helper(file, &group) // error: Sending 'file' risks causing data races
}
}
There's some related discussions about this in the forum (e.g. New task-creation APIs - #5 by philipp.gabriel) but no elegant solution can be found. I agree with jrose that withTaskGroup is nowadays best suited with Sendable inputs.