What is the potential issue with the following Swift code snippet concerning asynchronous operations and data race conditions?
iOS interview question for Intermediate practice.
Answer
A data race can occur on the purchaseState variable because it is a shared mutable state accessed by multiple concurrent tasks without synchronization.
Explanation
The code has a data race. The purchaseState property is a shared mutable state. The example usage shows one Task that will write to this property after a delay, and another Task that reads from it concurrently. Because there is no synchronization mechanism (like a lock or an actor) protecting purchaseState, one task could read the value while another is in the process of writing to it. This leads to unpredictable behavior; the second task might print false even after the purchase is complete. This is a classic data race condition.