Avatar ·

Equivalent of @synchronized from Objective-C in Swift: proper thread synchronization

Hi everyone! I recently switched from Objective-C to Swift and encountered a problem with synchronizing access to shared data from different threads. In Objective-C, I was used to using a simple construct:\n\n```objc\n@synchronized(self) {\n // critical section\n self.someProperty = newValue;\n}\n```\n\nIt guaranteed that only one thread executes the code inside the block at a time. Swift doesn't have this syntax. I know Swift has GCD (Grand Central Dispatch), but I'm not sure how to properly organize synchronization.\n\nProblem: I have a cache class that is accessed by multiple threads. Here's a simplified version:\n\n```swift\nclass Cache {\n private var storage: [String: Any] = [:]\n \n func set(value: Any, forKey key: String) {\n storage[key] = value\n }\n```