Shared state in the Sharing library cannot be mutated directly via its wrappedValue because doing so can lead to race conditions and data loss when multiple threads attempt to read, modify, and write the value simultaneously.
To ensure thread-safe mutation, you must use the withLock method. This method synchronizes access to the underlying shared storage for the duration of the provided lexical scope, ensuring that the read-modify-write cycle is atomic.
Because @Shared can be used anywhere (not just in @MainActor-bound SwiftUI views), using withLock is a required safety mechanism to prevent bugs in @Observable models, UIKit controllers, or background actors.
await withTaskGroup(of: Void.self) { group in
for _ in 1...1_000 {
group.addTask {
$count.withLock { value in
value += 1
}
}
}
}