Hello :D
I have a question about async and data race error on swift 6.0
when I have this code I have no Error but I am trying to send a noSendable object to async method so I can have data Race ?
struct TestView: View {
var body: some View {
Rectangle()
.task {
let mutableClass = MutableClass()
for _ in 0 ... 100 {
Task {
await Test().nonisolatedMehod(mutableClass: mutableClass)
}
}
}
}
}
class Test {
func nonisolatedMehod(mutableClass: MutableClass) async {
mutableClass.a = 1
print(mutableClass)
}
}
class MutableClass {
var a: Int = 0
}
and here I have an error
struct TestView: View {
let mutableClass = MutableClass()
var body: some View {
Rectangle()
.task {
for _ in 0 ... 100 {
Task {
print(mutableClass) // run on mainActor
mutableClass.a = 2 // run on mainActor
await Test().nonisolatedMehod(mutableClass: mutableClass) // ERROR ending 'self.mutableClass' risks causing data races
}
}
}
}
}
class Test {
func nonisolatedMehod(mutableClass: MutableClass) async {
mutableClass.a = 1
print(mutableClass)
}
}
class MutableClass {
var a: Int = 0
}
I don't undersand why
Am I supposed to be able to pass non-Sendable values to an async nonisolated method?
on this article : What is @concurrent in Swift 6.2? – Donny Wals
we have this sentence
This means that we must make the accessed or passed-in state
Sendable
, and that can become quite a burden over time. For that reason, making functionsnonisolated(nonsending)
makes a lot of sense. It runs the function on the caller’s actor (if any) so if we pass state from our call-site into anonisolated(nonsending)
function, that state doesn’t get passed into a new isolation context; we stay in the same context we started out from. This means less concurrency, and less complexity in our code.
so I am not sure to understand
I use swift 6.0 with strict concurency checking to complete
Because here I am update ma var on background multiple background thread I suppose to have dataRace ?