Hello everyone,
I got an error/warning of 'Mutation of captured a var in concurrently-executing code.' How does the compiler see the race condition happen? Maybe there's a fundamental misunderstanding of how Task works in swift, on my end.
Here's are some code snippets
actor
actor BackgroundBatchActor {
func act(input: String, action: @Sendable (String) -> String) {
let value = input + UUID().uuidString
let result = action(value)
print(result)
}
}
callsite:
Task {
var message: String? = nil
await actor.act(input: "very important message", action: {
message = $0 //<< warning/error
return $0
})
// more code...
}
My current understanding:
- When a task is created, it will have its own stack
- once an await happens, it will suspend the task. Since task's stack frame is not publicly available, there should not been two threads modifying the stack frame.
What's a good alternative for copying data out of a @Sendable closure?